Routing to different tabs in ReactJS

Solution 1:

The error clearly states what is wrong with your problem, you need to wrap your Routes within a div as a Router accepts only one child element.

Also in order to set the state in Provider you need to use setState or provide a handler

class Provider extends Component {
  state = {

    loggedIn: false,
    username: '',
    password: '',
    loginModalOpen: false,
    signupModalOpen: false,
    navbarOpen: false,
    activeTab: '3',

    setActiveTab: (tab) => {
       this.setState({activeTab: tab});
    }

    toggleLoggedIn: () => {
      this.setState({loggedIn: !this.state.loggedIn});
    },

    toggleLoginModal: () => {
      this.setState({loginModalOpen: !this.state.loginModalOpen});
    },

    toggleSignupModal: () => {
      this.setState({signupModalOpen: !this.state.signupModalOpen});
    },


    toggleNavbar: () => {
      this.setState({navbarOpen: !this.state.navbarOpen})
    },

    toggleTab: (tab) => {
      if(this.state.activeTab !== tab) {
        this.setState({activeTab: tab});
      }
    }
  }

  render() {
    return (
        <Context.Provider value={this.state}>
            {this.props.children}
        </Context.Provider>
    )
  }
}

also since you can't set state in render directly, you would need to create a component that handles this case

class Handler extends React.Component {
   componentDidMount() {
      this.props.setActiveTab(this.props.activeTab);
   }
   render() {
     return null;
   }
}

and your Router config would look like

<BrowserRouter>
   <div>
      <Route exact path='/' render={() => <Redirect to='/home/' /> } />
      <Route exact path='/home/' render={() => <Handler setActiveTab={setActiveTab} activeTab={'1'} />}/>
      <Route exact path='/popular/' render={() => <Handler setActiveTab={setActiveTab} activeTab={'2'} />}/>
      <Route exact path='/all/' render={() => <Handler setActiveTab={setActiveTab} activeTab={'3'} />}/>
   </div>
</BrowserRouter>