0

I am learning about React (Coming from ASP.NET). When I go to '/employee' it will display employee list table. But when I go to '/employee/create' it will display both the table and the create form. How to display only create employee form when I to '/employee/create' ?

export default class App extends Component {
static displayName = App.name;

render() {
    return (
        <Layout>
            <Route exact path='/' component={Home} />
            <Route path='/counter' component={Counter} />
            <AuthorizeRoute path='/fetch-data' component={FetchData} />
            <Route exact path='/employee' component={EmployeeIndex} />
            <Route path='/employee/create' component={EmployeeCreate} />
            <Route path='/employee/details/:id' component={EmployeeDetails} />
            
        </Layout>
    );
 }
}

2 Answers 2

1

To do that, you will need to add a <Switch> around your Routes:

import { Route, Switch } from "react-router";


<Switch>
   <Route exact path='/' component={Home} />
   <Route path='/counter' component={Counter} />
   <AuthorizeRoute path='/fetch-data' component={FetchData} />
   <Route exact path='/employee' component={EmployeeIndex} />
   <Route path='/employee/create' component={EmployeeCreate} />
   <Route path='/employee/details/:id' component={EmployeeDetails} />
</Switch>

It works just like a normal `switch-case, will only render the first matching path within your Routes.

Without <Switch> it will render ALL matching routes.

Sign up to request clarification or add additional context in comments.

1 Comment

I had to move <Route exact path='/employee' component={EmployeeIndex} /> to bottom, before </Switch>, to make it work.
1

Here what I use in my apps. Make separate components for all pages and import in App.js under src. Make use of state and props to store the data and create ID. Install npm i react-router-dom to access react route.

import { Switch, Route, Redirect } from "react-router-dom";
<Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/employee" component={Employee} />
    <Route exact path="/createEmployee" component={Create} />
    <Route exact path="/employeeDetails" component={Details} />
    <Redirect to = "/" />   
</Switch>
  1. for homepage - Home.js
  2. for employee list table - Employee.js
  3. create employee - Create.js
  4. go to employee's detail - Details.js
  5. Redirect to - will redirect to homepage if exact URL is not entered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.