Is there a way to use a variable as part of a value when setting state from props in ReactJS?

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I am very new to React. I am trying to make a reusable Checkbox component. These checkboxes are to send info to an API. I have a GET command on App.JS, to set state.

Here is a simplified version of my API

{
 "devices":[
   {
    "id":1,
    "valveA": true,
    "valveB": false,
    "valveC": true,
   },
   {
    "id":2,
    "valveA": false,
    "valveB": true,
    "valveC": false,
   }

 ]
}

I pass the props to the children like so:

render() {
    const {devices} = this.state;
    return (       
          <div >
            {devices.map(device => (
              <Device device={device} key={device.id} />
            ))}
          div>     
    );

I can make individual components for each checkbox and setting the checked state by setting individual state like so:

 state = { checked: this.props.device.valveA }

But that means I have to make a component for each 'valve' in my API. Ideally I would like to have one Checkbox component that I can reuse for all my "valves".

I've made a semi-working component by specifying the name of the valve as a prop:

<Device device={device} key={device.id} switchFor="valveA" />

And here is my component that successfully passes the change to the API, however I need to dynamically set the last part of the setState

this.props.device.{{{I WANT THIS TO BE DYNAMIC}}}

, otherwise all switches just get the state of valveA:

state = { checked: false };

  componentDidMount(){

    this.setState({ checked: this.props.device.valveStatus })
  }


  handleCheckboxChange = event => {
    const type = this.props.switchFor;

    const checkedStatus = event.target.checked;

    const deviceID = this.props.device.id;

    const obj = {};
    obj[type] = checkedStatus;

    this.setState({ checked: checkedStatus });

    axios
      
                                                
                                                
0 views
0 shares
profilepic.png
manpreet 2 years ago

 

Your explanation isn't really quite clear, but I think I can KIND OF understand what you're trying to do. If I'm wrong, just ignore me. So it seems like you want to be able to change which valve/switch of the device object to be displayed by your component. If that's the case, simply set that as a state. Off the top of my head, I can think of using a an array that mirrors your "devices" array:

this.state = {
    "devices":[
       {
        "id":1,
        "valveA": true,
        "valveB": false,
        "valveC": true,
       },
       {
        "id":2,
        "valveA": false,
        "valveB": true,
        "valveC": false,
       }
    ],
    "selectedValve": ["valveA", "valveB"]
}

Then when rendering your Device components, just do:

render() {
    const {devices} = this.state;
    return (       
          <div >
            {devices.map((device, ind) => (
              <Device device={device} key={device.id} switchFor={this.state.selectedValve[ind]} />
            ))}
          div>     
    );
}

To change the valve of a particular device, you can have:

handleSwitchChange(deviceInd, newValve){
    let copySelectedValve = [...this.state.selectedValve];
    copySelectedValve[deviceInd] = newValve;

    this.setState({
        selectedValve: copySelectedValve;
    })
}

To change the first device to valveB, you'd just do handleSwitchChange(0, "valveB"); To change the true/false of a valve of a device, you can write something like:


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community