Home > Software design >  Value from array object is not passing from Link to another component
Value from array object is not passing from Link to another component

Time:12-14

I am looking for the help to pass the data from one component to another component from link to in react router. What I nee is to take me to another page Newscontent when I click Link button in Titlecard with its values in item array object

App.js

<BrowserRouter>
        <Header />
        <Routes>
            <Route path="newscontent" element={<Newscontent />} />
        </Routes>
        <Footer />
</BrowserRouter>

Titlecard.js

const Titlecard = ({
  item: {
    id,
    imagePath,
    category,
    contentTitle,
    newsContent,
    authorName,
    time,
  },
}) => {
  return (
 <>
 <Link to={"/Newscontent"}
       state={{ item }}         
       >
       Read Article
</Link>

Newscontent.js

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

const Newscontent = (props) => {
  const location = useLocation();
  console.log(location);
  return <div>Articles dsfkdijsf sdjfdjsfjsd sdiofjidsjf</div>;
};
export default Newscontent;

CodePudding user response:

use useNavigation hook

const navigation = useNavigation()

const linkClick = () => {
   navigation.navigate('Newscontent', {state:item})
}

  return (
 <>
 <Link onClick={linkClick }      
       >
       Read Article
</Link>

Now use useParams to get the data

const Newscontent = (props) => {
  const {state}= useParams();
  console.log(state)

CodePudding user response:

as the react-router v5 documentation shows, you need to put the state inside the to props

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>
  • Related