user3507230
user3507230

Reputation: 83

React Router Declared but doesn't work please

Hello I want it to render InstrumentPage with no props when #/ is access but when #/ipb is access pass ipb as the props entity. But it's not working.

  render() {
    return (<React.Fragment>
      <HashRouter>
        <Switch>
          <Route path='/' render={(props) => <InstrumentPage {...props} />}/>
          {Object.keys(AppConfig).forEach((property) =>
            <Route path={property} render={(props) => <InstrumentPage {...props} entity={property} />} />)
          }
        </Switch>
      </HashRouter>
    </React.Fragment>);
  }

AppConfig

const AppConfig = {
  pb: {
    header: 'PBHeader',
    body: 'PBBody',
  },
  ipb: {
    header: 'IPBHeader',
    body: 'IPBBody',
  },
};    
export default AppConfig;

Upvotes: 2

Views: 70

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

You need to use map and return the Route, forEach won't return anything but undefined.

<Switch>
    <Route exact path='/' render={(props) => <InstrumentPage {...props} />}/>
    {Object.keys(AppConfig).map((property) =>
      <Route 
        path={`/${property}`} 
        render={ (props) => <InstrumentPage {...props} entity={property} /> } 
      />
     )
    }
</Switch>

Note: When you write path={property} which means path={ipb} or path={pb} which is incorrect path. Correct path should be path="/ipb" (Notice the slash), for this you need to do /${property} [contains back-tick] (using Template string).

Also add exact prop for your first Route otherwise it will going to match for all the Routes.

Upvotes: 5

Related Questions