0

I have used react-router to switch between 2 pages from the navbar. One of the pages is Home component. Now I have 3 columns as components in the homepage. Left column, middle column, and right column. By a button in the left column, I want to switch between two components in the mid column of the homepage.

function App() {
  return (
    <div className="App">
        <Router>
          <Navbar/>
          <Switch>

            <Route exact path="/">
              <Home/>
            </Route>
            <Route path="/FAQ">
              <FAQ/>
            </Route>

          </Switch>
        </Router>
    </div>
  );
}

At home components ->

class Home extends Component {
    render() {
        return (
                <div className={style.homeFlex}>
                    <LeftContainer/>

                    **<MidContainer/>**
                    **<AnotherMid/>**

                    <RightContainer/>
                </div>
            </div>
        )
    }
}

export default Home;

From a button inside LeftContainer, I want to switch between MidContainer and AnotherMid.

How can I use the router inside of an already routed component Linked from a sibling component? If there is a better way other than using the router to achieve the same, please share that also.

Rutvik Bhatt
  • 3,185
  • 1
  • 16
  • 28
Techies
  • 21
  • 4

1 Answers1

1

You don't need a route in this situation. You can use a state to render different components in your Home component.

Suppose your LeftContainer component looks like this:

class LeftContainer extends React.Component {
  render() {
    return (
      <div>
        <button onclick={() => this.props.handleSwitchComponent()}>
          click here to change component
        </button>
      </div>
    );
  }
}

You'll need to pass a function through props, then you can use this component in Home component like this:

class Home extends Component {
  state = { IsMidContainerVisible: true }

  handleSwitchComponent = () => {
    this.setState(({ IsMidContainerVisible }) => ({
      IsMidContainerVisible: !IsMidContainerVisible;
    }));
  };

  render() {
    return (
      <div className={style.homeFlex}>
        <LeftContainer handleSwitchComponent={this.handleSwitchComponent} />

        {/* Now here we need to specify when we want to show components */}
        {this.state.IsMidContainerVisible ? <MidContainer /> : <AnotherMid />}

        <RightContainer />
      </div>
    );
  }
}

export default Home;
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129