Adn
Adn

Reputation: 135

React nested route render the parent component with the child component

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>
    );
 }
}

Upvotes: 0

Views: 1290

Answers (2)

Ryan Le
Ryan Le

Reputation: 8422

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.

Upvotes: 1

kaych22
kaych22

Reputation: 61

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.

Upvotes: 1

Related Questions