3

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>
  );
Cruz
  • 85
  • 1
  • 1
  • 5

1 Answers1

7

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>
}
buzatto
  • 9,704
  • 5
  • 24
  • 33
  • 1
    This worked! There's just a curly bracket missing in the link tag. This should do: – Cruz Feb 16 '21 at 11:11