I’m trying to dynamically add and remove react components called Sessions by adding Sessions to an array.
I want to be able to remove the last Session from the array when I press my deleteSessionButton but, it seems that if I have more than one Session rendered on the page, when I press deleteSessionButton it resets the page completely.
Here’s the code as it exists inside my Program component
const Program = () =>{
const [sessions, setSessions] = useState([]);
const addSessions = () => {
const newSession = <Session key={generateKey()} />;
setSessions(prevSessions => [...prevSessions, newSession]);
};
const deleteLastSessions = () => {
if (sessions.length > 0) {
setSessions(prevSessions => prevSessions.slice(0, -1));
}
};
const generateKey = () => {
return uuidv4();
};
const AddSessions = () => {
return (
<button className="addsessions" onClick={addSessions}>
Add Session
</button>
);
};
return(
<form>
<input type="text" placeholder="Program Name"></input>
{sessions.map((SessionsComponent) =>
<React.Fragment key={generateKey()}>{SessionsComponent}</React.Fragment>
)}
<AddSessions />
{sessions.length > 0 && (
<button className="deleteSessionsButton" onClick={deleteLastSessions}>
Delete Last Session
</button>
)}
<SaveProg />
</form>
);
};
For a while I thought it was an issue with keys. At first I created them based of the index. Then I tried to use a counter and now I just use UUID but, that’s obviously not the problem. I’m still learning so I’m sure there some fundamental misunderstanding here. I’m just hoping someone can look at this and tell me what I’m misunderstanding about React and js.
>Solution :
You have a form and a button inside of it, and the thing is that this button without "type" has a default "type" which is "submit" in most of the modern browsers (and in the W3C specification). So your form is basically submitted and the page is reloaded.
To fix – just specify the "type" of the button:
<button
type="button"
className="deleteSessionsButton"
onClick={deleteLastSessions}
>
Delete Last Session
</button>