Home > database >  Multiple instances of react component with different props doesn't work properly
Multiple instances of react component with different props doesn't work properly

Time:04-29

I have difficulty with multiple instance of components despite using different key values for them. For example, I make 2 simple pages and pass different props. However, only one of them would log or alert. Shouldn't be one message from each component with their props? What did I miss here?

class Temp_page extends Component {
  constructor(props) {
      super(props);   
      console.log("props", props)
      alert("this.props.tag"   this.props.tag);    
  }
  render() {
    return ( <div id={this.props.tag}> {this.props.tag} </div>);
  }
}

And the routes:

      <Route key="11" path="/temp_1" element = {
        <Temp_page tag={"temp_1"}/>
      }/>     

      <Route key="22" path="/temp_2" element = {
        <Temp_page tag={"temp_2"}/>
      }/>     

CodePudding user response:

This is expected. The Route component from react-router is designed so that it only renders the route(s) that match. Others do not render at all.

When you do element = {<Temp_page tag={"temp_1"}/>}, that does not immediatley call the constructor for Temp_page. It just creates an element; in other words, a small object describing what that part of the page should look like. <Route> then checks the url. If the url matches, the <Route> will return the element you asked it to render, and then react will mount the component, calling its constructor. If instead the url does not match, <Route> returns null. The element ends up not being used.

  • Related