0

In react i want to pass a reference of component to routes component . But when i route to path such as '/' it re render the passed component so starts with 0 again. Here is a Link of Working example https://codesandbox.io/s/884yror0p2 Here is a code, whenever i route from Home-->About the about counter starts with 0.

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

class Dummy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      c: 0
    };
    setInterval(() => {
      this.setState({ c: this.state.c + 1 });
    }, 1000);
  }

  render() {
    return <h1> Counter {this.state.c}</h1>;
  }
}

class BasicExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // com: <Dummy /> this technique also not work
    };
  }
  render() {
    let com = <Dummy />;
    return (
      <div>
        <Router>
          <div>
            {com}
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/about">About</Link>
              </li>
            </ul>

            <hr />
            <Route
              exact
              path="/"
              // render={() => <Home com={com} />} //this also not work
              component={props => <Home {...props} com={com} />}
            />
            <Route path="/about"
              component={props => <About {...props} com={com} />}             
             />
          </div>
        </Router>
      </div>
    );
  }
}

class Home extends React.Component {
  render() {
    return (
      <div>
        {this.props.com}
        <h2>Home </h2>
      </div>
    );
  }
}

class About extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }
  render() {
    return (
      <div>
        {this.props.com}
        <h2>About</h2>
      </div>
    );
  }
}

ReactDOM.render(<BasicExample />, document.getElementById("root"));
  • Depending on the meaning of this counter, it would be better solved with redux. What kind of event is the instantiation of the dummy component? With redux you would pass in the counter via mapStateToProps to any connected component and increase it via actions. – timotgl Mar 31 '18 at 09:01

2 Answers2

1

You can’t pass a component by “reference”. However, if you would like to have the same data between all the components you could initialize your state in the parent component (BasicExample) and pass it down or use a state container like Redux.

Kerry Gougeon
  • 1,317
  • 12
  • 18
1

You can the component down but the component will also go through a mounting process that will invalidate the state that you have stored in it. If you need to hold the state, it should be stored in the parent component.

const Router = ReactRouterDOM.HashRouter;
const Route = ReactRouterDOM.Route;
const Link = ReactRouterDOM.Link;

class Dummy extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      c: props.c || 0
    };
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.c !== nextProps.c) {
      this.setState({
        c: nextProps.c
      });
    }
  }
  render() {
    return <h1> Counter {this.state.c}</h1>;
  }
}

class BasicExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
    setInterval(() => {
      this.setState(prevState => {
        return {
          counter: prevState.counter + 1
        };
      });
    }, 1000);
  }
  render() {
    let Com = <Dummy c={this.state.counter} />;
    return (
      <div>
        <h2>Main App</h2>
        <Router>
          <div>
            {Com}
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/about">About</Link>
              </li>
            </ul>

            <hr />
            <Route
              exact
              path="/"
              // render={() => <Home com={com} />} //this also not work
              render={props => (
                <Home {...props} c={this.state.counter} Com={Dummy} />
              )}
            />
            <Route
              path="/about"
              render={props => (
                <About {...props} c={this.state.counter} Com={Dummy} />
              )}
            />
          </div>
        </Router>
      </div>
    );
  }
}

class Home extends React.Component {
  render() {
    const Com = this.props.Com;
    return (
      <div>
        <h2>Home </h2>
        <Com c={this.props.c} />
      </div>
    );
  }
}

class About extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const Com = this.props.Com;
    return (
      <div>
        <h2>About</h2>
        <Com c={this.props.c} />
      </div>
    );
  }
}

ReactDOM.render(<BasicExample />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.2.0/react-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.2.2/react-router-dom.js"></script>
<div id="root"></div>

Few things to note here are:

  1. Use render property of Route to pass in any props

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop

  1. Use function version of setState to refer to prevState
Agney
  • 18,522
  • 7
  • 57
  • 75