I am making an app in which I have 3 buttons of which 2 are of importance to my problem. One button should add elements to the website the user is viewing and the other should remove elements.
I'm new to React and feel I have a grasp of the basics but clearly need to get my head around it better.
My first intuition was to just create an Array into which I could push elements and then just have that array in one of my JSX.Elements as the content of it.
That looked something like this:
My JSX.Element:
answerView = (
<div>
<button onClick={this.removeIceCream}>Poista jäätelö!</button>
<button onClick={this.addIceCream}>Lisää jäätelö!</button>
<button onClick={this.keyInput}>OK</button>
<div>{this.iceCreamCount}</div>
</div>
);
The function to just add something to the element.
addIceCream() {
this.iceCreamCount.push(<li>"Jäätelö"</li>);
}
However this ends up in the array iceCreamCount updating but not being displayed in the DOM. Does React not ehmm "react" to changes in elements and only changes in its State or Properties?
Does this mean that in order to manipulate the DOM elements in accordance to user input my array containing the elements also needs to be a state variable?
If the above is indeed impossible then I would like help with how to do it properly in React and below is my attempt at doing so.
I've checked a few tutorials and examples and came up with something like this:
addIceCream = () => {
this.setState(state => {
const iceCreams = state.iceCreams.concat(state.iceCream);
return {
iceCreams,
iceCream: 'Jäätelö',
};
});
};
With my state declaration looking like this:
this.state = { doorView: true, bunnyView: false, answerView: false, iceCream: "Jäätelö", iceCreams: [] };
During writing this problem I actually got this seemingly working but I would also like to understand how and why this works as I am not really confident in my knowledge.
However I don't feel like I've grasped what exactly is happening here. I'm not very confident with arrow-functions (if anyone has a great simple tutorial on them please do link) and while I think I've gathered that because data is supposed to be immutable in React is why I need to use
concat()
to create a new array that is a copy of the old one + my added element. But why do I need to return()
the state variables and why are there so many arrow functions being thrown around (see below for my condensed "what I would like to know list")?
What I would like to know
- Is the first part of my question a workable way in React or is it simply the wrong approach completely? If it can be done, I would appreciate if someone would show me how and what are my mistakes in my thinking.
- Why and how does the second part of my question work? If someone had the time and patience to go through it line by line starting from:
addIceCream = () => {....
and tell me what is happening that would help me a lot in understanding and learning.