Dmitry Malugin
Dmitry Malugin

Reputation: 921

How to navigate nested components with react-router 4

I have a screen with buttons, common background and common title and changing nested components. Inside this screen I want to change nested components with a click of a button. Nested components must change each other in a circle with left and right button. So far I did a lots of attempts to achieve this ( I try to do it with withRouter), I give you code only of one of my attempts, but all of them didn't work. I don't get any errors, I see route in browser is changing but screen doesn't, I see only the first nested component. There is questions about this on SOF, but they related to older version of react-router. Here my code, if you need more information feel free to ask in comments.

import React, { Component } from 'react';

import { Link, 
         BrowserRouter as Router,
         Route,
         Switch,
         withRouter } from 'react-router-dom';

import Info1 from './info/info1';
import Info2 from './info/info2';
import Info3 from './info/info3';
import Info4 from './info/info4';


class Info extends Component {

   constructor(props) {
    super(props);

    this.currentIndex = 1;

  }




  componentDidMount() {


  }

  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }






  render() {


    return (
      <Router>
       <div className="info-common">
           <img className="game-title info-game"/>
           <Switch>
                 <Route path="/info/1" component={ Info1 }/>
                <Route path="/info/2" component={ Info2 }/>
                <Route path="/info/3" component={ Info3 }/>
                <Route path="/info/4" component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
       </div>
      </Router>
    );
  }

}


Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.isRequired,
};

export default withRouter(Info);

EDIT: While I accepted given answer, I didn't test it, in my project I used this solution:

app.js 

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

...


render() {

    return (
      <div id='game-container' width="1236" height="634">
        <Router>
        <div>
          <Route path="/info" component={ Info }/>
        </div>
        </Router>
      </div>
    );
  }

Then in Info itself:

Info.js

class Info extends Component {

   constructor(props) {
   super(props);

   this.currentIndex = 1;

  }





  leftHandler() {
    console.log("left click");
    var temp = this.currentIndex;
    this.changeScreen(--temp);
  }

  rightHandler() {
    console.log("right click");
    var temp = this.currentIndex;
    this.changeScreen(++temp);
  }

  changeScreen(index) {

    const numberOfScreens = 4;

    if(index < 1)
        this.currentIndex = numberOfScreens;
    else if(index > numberOfScreens)
        this.currentIndex = 1;
    else
        this.currentIndex = index;
    this.props.history.push("/info/" + this.currentIndex);
  }


  render() {


    return (
       <div className="info-common">
           <img className="game-title info-game" src={ this.drawGame() }/>
            <Switch>
                <Route path={`${this.props.match.path}/1`} component={ Info1 }/>
                <Route path={`${this.props.match.path}/2`} component={ Info2 }/>
                <Route path={`${this.props.match.path}/3`} component={ Info3 }/>
                <Route path={`${this.props.match.path}/4`} component={ Info4 }/>
            </Switch>
            <Link to="/rings"><button className="back-info-btn">назад</button></Link>
            <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
            <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
       </div>
    );
  }

}

Info.propTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired,
    }).isRequired,
  location: React.PropTypes.object.isRequired,
};

export default withRouter(Info);

Upvotes: 0

Views: 941

Answers (1)

Alexander Gundermann
Alexander Gundermann

Reputation: 286

If you wrap a component in withRouter, you can only use it inside a <Router>, just like <Route>s etc.

To get your example working, you need to make <Info> a child of <Router>, since it uses withRouter. First, remove the <Router> from the render method, and just render the <div> as the top-level component:

render() {
  return (
    <div className="info-common">
      <img className="game-title info-game"/>
      <Switch>
        <Route path="/info/1" component={ Info1 }/>
        <Route path="/info/2" component={ Info2 }/>
        <Route path="/info/3" component={ Info3 }/>
        <Route path="/info/4" component={ Info4 }/>
      </Switch>
      <Link to="/rings">
        <button className="back-info-btn">назад</button>
      </Link>
      <button onClick={ this.leftHandler.bind(this) } className="left-info-btn"></button>
      <button onClick={ this.rightHandler.bind(this)} className="right-info-btn"></button>
    </div>
  )
}

Then, wherever you render <Info />, render <Router><Info /></Router> instead. Or, add an extra component that renders the two, and use that component instead of <Info />.

// Option 1: render <Router> wherever you use <Info>
import Info from './info';
...
ReactDOM.render(<Router><Info /></Router>);

// Option 2: add another component that wraps <Info> in a Router,
// either as the new export of the module, or as a new module
const App = () => (
  <Router>
    <Info />
  </Router>
);
export default App;

Upvotes: 1

Related Questions