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.
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.
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:
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:
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:
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.
manpreet
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 onApp.JS
, to set state.Here is a simplified version of my API
I pass the props to the children like so:
I can make individual components for each checkbox and setting the
checked
state by setting individual state like so: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:
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
, otherwise all switches just get the state of valveA: