after clicking on button I want add new line into form.
I created and imported Lines component and now after clicking on button I want add 1 into form.
I was able wrote this. But this doesnt work, it will not even show error. and I have no idea how to fix it.
useState is empty array, and after clicking button I wanna add and store new component.
Thank you
const Form = () => {
const [lines, setLines] = useState([]);
const addLine = () => {
setLines(lines => [...lines, <Lines />]);
};
return (
<div>
<form>
{lines.map(line => {
{line}
})}
</form>
<button onClick={addLine}>
</button>
</div>
);
};
>Solution :
{lines.map(line => { {line} })}
It’s not working because you have no return statement in your map function. You would write this as:
{lines.map(line => {
return line
})}
And since at that point the map function isn’t changing anything, you can just use the original array.
{lines}
But i would urge you not to store elements in react state. You don’t have any props in the current example, but as soon as you do it will become extremely easy to have bugs caused by stale props.
Instead, your state should be the minimum amount of data needed to describe the page, and then the elements should be created during render. For example, If each line has some data associated, continue to use an array but just store the data not the elements:
const Form = () => {
const [lines, setLines] = useState([]);
const addLine = (name) => {
setLines(lines => [...lines, { name }]);
};
return (
<div>
<form>
{lines.map(line => {
return <Lines name={line.name} />
})}
</form>
<button onClick={addLine}>
</button>
</div>
);
};
Or if there’s no data about each one, then you could change the state to be just a number:
const [numLines, setNumLines] = useState(0);
const addLine = () => {
setNumLines((prev) => prev + 1);
};
const lines = [];
for (let i = 0; i < numLines; i++) {
lines.push(<Lines />);
}
return (
<div>
<form>{lines}</form>
<button onClick={addLine}></button>
</div>
);