How to make multiple react Route where the path is almost same except the id

Viewed 47

I have an object called machines object.This object has it's unique key.Now i want to make Route like path={"/machine" + key} for all the machines.I am trying to do it like the following but it doesn't work

{Object.keys(this.state.machines).forEach((key, index) => {
  // console.log(this.state.machines[key].machineNo)
  <Route
    exact
    path={"/machine" + key}
    component={() => (
      <MachineComposition machine={this.state.machines[key]} />
    )}
  />
})}
1 Answers

Issue

You are using Array.prototype.forEach instead of Array.prototype.map to map the this.state.machines array to JSX. The .forEach callback is missing a return statement, but that wouldn't matter as .forEach is a void return so no routes would be returned to be rendered to the DOM anyway.

Solution

Use .map to map the machines array to JSX. Use the render prop if you are passing additional props to the routed component, and don't forget to also pass along the route props (i.e. history, match, location) if the component needs them.

{Object.entries(this.state.machines).map(([key, machine]) => {
  return (
    <Route
      exact
      path={"/machine" + key}
      render={(props) => (
        <MachineComposition machine={machine} {...props} />
      )}
    />
  );
})}

Suggestion

Since all these routes are effectively the same it would be better to render a single route where the machine key is a route path parameter, and the MachineComposition uses the params to access the machine key and get the specific machine.

Example:

<Route
  exact
  path="/machine/:key"
  render={(props) => {
    const machine = this.state.machines[props.match.params.key];
    return <MachineComposition machine={machine} {...props} />
  }}
/>
Related