I’m new in react.
What should i do to display a state in dynamic context?
In the example, when props.something changes, set displayed text state1 depending on the props.something value.
If props.something is NOT 1, put a checkbox named checkbox1 in state1 and show the checked state.
Actually in this case, checked state doesn’t change even if the checkbox1 was clicked.
Any ideas?
const Child = (props) => {
const [checked, setChecked] = useState(false);
const [state1, setState1] = useState(<></>);
useEffect(() => {
if(props.something === 1){
setState1(<div>something is 1!</div>);
}
else{
setState1(<div>
<input type="checkbox" name="checkbox1" onChange={() =>
setChecked((prevState) => return !prevState;)
} defaultChecked={false} />
State is {checked ? "TRUE" : "FALSE"}
</div>);
}
}, [props.something]);
return (<>{state1}</>);
}
EDIT:
Thanks to give some suggestions!
In actual project, the Child component is used to show data-fetching state — Parent component fetches some data from the online database. Parent component sends "props.something === 1" to the Child if the app starts to fetch data, and sends except 1 when the task was done.
I use checkbox1 to delete the item got from the database.
2
Answers
I think you don’t have the right approuch to this situation, you can conditionaly render things with the states, is not needed that you use a state to keep your html I did a bit of refactor on your code
on this script we have a childrenComponent that can be imported or defined in the same file, that component get a ‘something’ prop and set a set based in that. Then render conditionaly the text or the checkbox usin a ternary operator.)
You can just check
props
to understand what you need to render.