Peter Kartalov
Peter Kartalov

Reputation: 31

How to pass route props into my functional component

Link component

   return (
                      <div key={driver.id}>
                        <Link to={"/drivers/" + driver.id}>
                          <OurStaffList driver={driver} />
                        </Link>
                      </div>

App.js

   <Switch>
      <Route exact path="/" component={HomePage} />
      <Route path="/archived-routes" component={ArchivedRoutes} />
      <Route path="/find-routes" component={FindRoutes} />
      <Route path="/signup" component={SignUp} />
      <Route path="/signin" component={SignIn} />
      <Route path="/drivers/:driver_id" component={DriverProfile} />
    </Switch>

And now here in the component where i need the route id, im getting 'error not recognized params...' Can someone give me an idea how i can get the route props into the component so i can render the correct driver profile ?

  const DriverProfile = ({ driver, getDrivers }) => {
  useEffect(() => {
    getDrivers();

    // eslint-disable-next-line
  }, []);
  console.log();
  return (
    <div className="col s12">
      <ul className="with-header">
        {driver.drivers &&
          driver.drivers.map(driver => {
            return <DriverProfileList driver={driver} key={driver.id} />;
          })}
      </ul>
    </div>
  );
};

DriverProfile.propTypes = {
  driver: PropTypes.object.isRequired
};

const mapStateToProps = (state, ownProps) => {
  let id = ownProps.match.params.driver_id;
  console.log(id);
  return {
    driver: state.driver
  };
};

Answered by user6136000. Thanks

Upvotes: 2

Views: 8534

Answers (2)

user6136000
user6136000

Reputation: 115

https://reacttraining.com/react-router/core/api/Hooks/useparams

So, in your DriverProfile function component:

let { driver_id } = useParams();

Upvotes: 6

Harion
Harion

Reputation: 225

You can access all routing parameters in component by wrapping it with https://reacttraining.com/react-router/core/api/withRouter

Upvotes: -1

Related Questions