Cruz
Cruz

Reputation: 105

React: how to pass props through a Link from react-router-dom?

I'm trying to pass title from props to my Dishes component using <Link> but can't find a solution. Any sugestions?

import { Link } from "react-router-dom";

const Category = ({ title }) => {
  return (
    <Link to="/dishes">
      {title}
    </Link>
  );
};

export default Category;

App.js is looking like this:

return (
    <Router>
      <div className="App">
        <Route
          path="/"
          exact
          render={(props) => (
              <Categories recipes={recipes} />
          )}
        />
        <Route path="/dishes" component={Dishes} />
      </div>
    </Router>
  );

Upvotes: 3

Views: 14322

Answers (1)

buzatto
buzatto

Reputation: 10382

Link can pass a state object that can be retrieved from you component through location:

import { Link } from "react-router-dom";

const Category = ({ title }) => {
  return (
    <Link to={{ pathname: "/dishes", state: { title } }}>
      {title}
    </Link>
  );
};

export default Category;

Then you can extract state from location prop. But since you are passing this value only when you click on Link, state can be undefined if you access the Route directly. This way you may want to provide a defaultValue in these cases:

const Dishes = ({location}) => {
  const { title = 'defaultValue' } = location.state || {}

  return <div>{title}</div>
}

Upvotes: 7

Related Questions