Prevent a component from re-mounting React

Hello everyone, I am having an issue I can find very little info with on google.
When I navigate to the cart from my shop component, it will remount it and reset all the buttons.
I want to make it so you can switch from the services to the cart as many times as you want without it erasing what you’ve selected.
Does anyone know what I mean here?
Thanks in advance.

My full code is here:

Not sure I understand the question. What is it erasing?

  1. On CodeSandbox you can use Shift + Alt + F to format your code. It should also auto-format on save. You really need it (again).

  2. Try switching between services and cart a couple of times, now add a product. You should see it was added multiple times.

In the Services component don’t use addEventListener. Make the map callback function an arrow function, now add an onClick to the button and call addToCart you are passing down as a prop onClick={e => this.props.addToCart(e)}

In fact, you can remove all the code before the render, which also means it does not need to be a class and can just be a stateless function component. You have other components where you add constructors and state but do not need them. If all the component does is use props that were passed down to render something or trigger a callback you do not need the constructor or state in the component.

1 Like

I’m not sure how you can not understand my question yet answer all of my questions completely. Thanks for your help!
And for the record, I did use prettier on my vscode and it looks much better, I just put it all on codesandbox to be visible. I didn’t know about that feature

If it is “remounting” that means that it unmounted. You need to check into the docs of whatever nav you’re using. If you can’t do that, you’ll have to find a way to preserve the data so you can repopulate it.

Though I do have one followup question. When you say “Make the map callback function an arrow function” Do you mean changing: ?

if (this.props.propdata) {
      var serviceitems = this.props.propdata.main.serviceitems.map(function (
        serviceitems
      )

I just wasn’t sure. I found the issue when looking at the code so I thought I would mention it even if it was not the issue you were talking about.

Yes, change the map callback function(serviceitems){} to (serviceitems) => {}

1 Like

Can I ask your help a little bit on the syntax? I am not used to writing arrow functions. When I write it as:

(function (serviceitems) =>  {

It throws a syntax error and I’m not sure why

nevermind, I didn’t know you had to take the ‘function’ out