I want to update and re-render for loop test condition on hook state update. After I update state hook the state is rerendered but I want to the loop to be rerendered too. I make a form. The length of the form depends on what number I enter on input.
Here is what I tried:
const [formLength, setFormLength] = useState(0); let eachForm = () => { for (let x = 0; x < formLength; x++) { return <div>{x+1} inpute</div>; } }; useEffect(() => { eachForm(); }, [formLength]); {formLength <= 0 ? (<>Zeroo</>) : (<><eachForm /></>)}
Advertisement
Answer
There is no need for the useEffect
hook here, it’s not doing anything for you. You can render directly the JSX from the formLength
state. eachForm
also isn’t a valid React component, so it can’t be used like <eachForm />
. The for-loop
will also return during the first iteration and not return an array of div
elements like I suspect you are expecting.
Example:
const [formLength, setFormLength] = useState(10); return ( <> {formLength ? Array.from({ length: formLength }).map((_, i) => ( <div key={i}>{i+1} input</div> )) : <>Zero</> </> );