0

I have this state inside a class component. It has two keys:

this.state = {
  component: <MainScreen handleComponent={this.handleComponent} />,
  position: [],

}

And I render on screen the value of component.

Every time I click a button, the event handler handleComponent does two things: updates the state 'component' value with a new component to render, and the second thing it does is to add that new component to the 'position' array, so I can have a path of components that the user went through and were rendererd on screen.

My purpose is to have a BACK button that renders the previous component on screen and the way I'm trying to do it is to read the values in the array position.

My problem is that if I do a console.log(this.state position) I get an Object.object or undefined or not a value at all. I don't get something like even that these values are inside the array position because I can see them inside the state when I go through the components when I click on them.

The event handler looks like this:

handleComponent = (value) => {
this.setState({component: value});

if (this.state.component == <MainScreen />) {

    alert("it works")

  }else {this.state.position.push(value)};

}

I can push the tags that are passed as 'value' to the 'position' and get the array with all the components that were rendered on screen, but I can't do something like

if (this.state.component == <MainScreen />) {something somethig}

Why that happens? It seems like I can't equal React component tags with something to get true or false, or even get a tag from the array but I can push elements in it.

Thanks!

Huagru
  • 3
  • 1
  • 3
  • This is less of a React question and more of Javascript question, the kind of comparison you are doing above will never work, you're basically comparing two objects which are different instantiations, and objects are compared by identity/reference, so that comparison will never be true. – Cory Harper May 26 '22 at 16:31
  • https://stackoverflow.com/a/201471/11753100 might be helpful in understanding what I mean, though I wouldn't follow through and start trying to do a deep comparison of the components, I'd try to think of a different solution for keeping track of what component the user is viewing. – Cory Harper May 26 '22 at 16:34

0 Answers0