Is it appropriate to have a jsx component in your state?
const [personalDetailsArray, setPersonalDetailsArray] = useState([
<PersonalDetails key={id}/>]);
For example, (see above) having a state array that can update and help you render components as your state changes.
CodePudding user response:
Not a good idea to store your dynamic components on state, instead you can use function to render dynamically a component depending on your state/props data.
You can do it like this
const YourComponent = (props)=>{
const [personalDetailsArray, setPersonalDetailsArray] = useState([
]);
const getDynamicComponet= (id)=>{
switch (id){
case id === 'personalDetails':
return <PersonalDetails key={ id } />
case id === 'component_1':
retrun ...
case ...
}
}
const id = 'personalDetails'// or from props , or from state
return (
getDynamicComponent(id)
)
}
CodePudding user response:
In general, state should rather be used for storing the state of data in your app.
Then use something like map on the data to return the relevant UI components.
E.g.
const [personalDetails, setPersonalDetails] = useState([<your data for personal details>]);
return personalDetails.map(personalDetail=><PersonalDetails key={personalDetail.id}/>)
By doing this way you make it easier for React to compare changes to state (as you're only storing the data now). Moreover the code is better decoupled with rendering and data split out.
More information can be found here