Home > Net >  dynamic/variable form in react
dynamic/variable form in react

Time:11-14

I hope you are fine. I have a question. I'm new to react yet. I have 87 devices. And these devices have their own characteristics. In the database (MYSQL), I separated them all by id. When I select from dropdown in React (for example, X device), I want the relevant form to come. But I have no clue how to do it. Does anyone have an example or guide? It's like making 87 components messes things up. There must be an easy way. Thank you.

child-component , yup , react-hooks-form

CodePudding user response:

So before doing anything in React, you should create a rest API with an end point that you can call from your React App to query your data in your MySQL database (use express or fastify to do that quickly).

Because, you simply can't query a database from a web client (for security purposes)

Then, In React after you fetched you data you can create a generic component called deviceCard for instance.

And from that, you'll be able to iterate through your array of devices via a map and create new instance of your deviceCard

{devices !== null && devices.map(device => {
                return (
                    <div key={device.id}>
                        <deviceCard device={device}/>
                    </div>
                )
            })}

I did that here for full exemple: https://github.com/ValentinM27/fox-pro/blob/main/frontend/src/components/enterprises/consult.component.jsx

So you create a state, then you fetch you data and store in the state (devices in my exemple) and then in your "HTML" part create a map based on your state variable.

Now you're sure you queried your data correctly, you can juste create a dropdown in your map instead of generic component.

Hope I helped you, good luck

  • Related