Doe
Doe

Reputation: 163

sending props via the react-router Link component

I have a problem with sending props through the Link component of the react-router. This is my component that is responsible for displaying a specific element:

const ItemRecipe = ({ recipe }) => {
  const { label, image } = recipe.recipe;
  return (
    <li>
      <p> {label} </p>
      <img src={image} alt="food" />


      <Link to={{pathname: `/meals/${label}`, params: recipe }}>

        <p>next</p>
      </Link >
    </li>
  );
}

After clicking on I want to open the page with a specific recipe. This component looks like this

class DetailsRecipe extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recipe: props.match.params.recipe
    }
    console.log(this.state.recipe);
  }
  render () {
     <div>
         lorem lorem

      </div>
    )
  }
}

console.log(this.state.recipe) displays undefined. how to fix this error? How to correctly send data through the Link component of the react-router?

I looked at similar topics on a stackoverflow but it did not help to solve my problem

Upvotes: 0

Views: 608

Answers (1)

Bj&#246;rn Hei&#223;
Bj&#246;rn Hei&#223;

Reputation: 1728

Have another look at the documentation of the Link component. The properties allowed inside the to object are:

  • pathname: A string representing the path to link to.
  • search: A string representation of query parameters.
  • hash: A hash to put in the URL, e.g. #a-hash.
  • state: State to persist to the location.

I guess you want to use state instead of params.

EDIT:

So your code would look like this:

<Link to={{pathname: `/meals/${label}`, state: {"recipe": recipe} }}>

Then you can access the state inside the linked component like this:

this.state = {
  recipe: props.location.state.recipe
};

Upvotes: 1

Related Questions