0

I am trying to send props to component with NavLink.

 <NavLink to={{pathname :"/wind", state:{from: "This is my props"}}} >Wind</NavLink>

and I want to get it in this component,


import React from 'react';
import { useLocation} from "react-router-dom"

const Wind = () =>{
    const location = useLocation();
    const {from} = location.state;
    console.log({from})

  return (
    <div className="Wind">
      <h1>Wind</h1>
    </div>
  );
}

export default Wind;

unfortunatelly this give me result enter image description here

so I try it like this

import React from 'react';

const Wind = (props) =>{

//console.log(props.location.state)

  return (
    <div className="Wind">
      <h1>Wind</h1>
    </div>
  );
}

export default Wind;

console log in ths case is undefined. I don´t know why it is not working any ideas?

Michaela
  • 309
  • 3
  • 16
  • This ticket is a duplicate, you can refer to https://stackoverflow.com/questions/70054635/passing-props-with-navlink-in-react-router-dom-v6 https://stackoverflow.com/questions/59701050/how-to-pass-data-from-a-page-to-another-page-using-react-router – poo Apr 26 '22 at 10:33
  • I saw it but I am still getting the same error "Cannot read properties of null" – Michaela Apr 26 '22 at 10:46
  • Firstly, which react-router-dom version you are using. And can you share more about this code maybe there is some other issue? – poo Apr 26 '22 at 11:41

1 Answers1

4

In the new version, the state is passed as a separate prop. Try using

<NavLink to={{pathname :"/wind"}}
 state={{from: "This is my props"}} >Wind</NavLink>

And the component try fetching like this

import React from "react";
import { useLocation } from "react-router-dom";

const Wind = () => {
  const location = useLocation();
  const { state } = location;
  console.log(state.from);

  return (
    <div className="Wind">
      <h1>Wind</h1>
    </div>
  );
};

export default Wind;
poo
  • 1,080
  • 3
  • 10
  • and how the component should look like? How I display it in component? – Michaela Apr 26 '22 at 10:42
  • 1
    updated my answer try this out. – poo Apr 26 '22 at 11:45
  • that is workig very well but what if I want to send more props something like this doesn´t work and it always see only first data ""state={{ fromTemperature: data, dailyForecast:dataWeather.daily }}"" – Michaela Apr 27 '22 at 11:49
  • you can fetch all the data from your state object. try console.log(state) you should get all the data of that object. – poo Apr 27 '22 at 13:18