Simple Conditional Routing in Reactjs

后端 未结 6 692
一整个雨季
一整个雨季 2020-11-28 05:01

How to make conditional Routing, if and only if some conditions satisfies then only routing should happen. for example, if and only if the user enters the correct credential

6条回答
  •  野性不改
    2020-11-28 06:01

    The best and simple thing you can do is to create a state variable login and route based on the boolean values. the logic to set is up to you. i can show an example of simple routing based on condition. I store my pages in a array and use the map function to switch to different routes. For an example I have inserted my DesignerHome.js for your reference


    This is my App.js

    import React,{Component} from 'react';
    import{BrowserRouter as Router,Switch,Route,Redirect,}   from 'react-router-dom'
    import MainHome from './MainHome'
    import DesignerHome from './designer/DesignerHome'
    
    export default class App extends Component{
      constructor(){
        super()
        this.state={
          login : true,
          r_page :[
            {
              path :'/designerhome',
              component : DesignerHome,
            },]
          }    
        } 
      render(){  
        return(      
          
              
                          
              {this.state.r_page.map((item , i)=>(this.state.login?
     :   ))}
                    
           
    
        )    
      }
    }
    
    
    

    This is my DesignerHome.js

    import React,{Component} from 'react';
    
    export default class DesignerHome extends Component{
      render(){
        return(
            
    designer home
    ) } }

提交回复
热议问题