Home > Mobile >  How to pass data from component to another component in react hooks with onClick
How to pass data from component to another component in react hooks with onClick

Time:02-03

On click on the blogItem, how can I pass data from blogItem.js component to blogDetails.js component ? However the blogItem component is imported in Home.js component. May I know where do I add the click action ? Could someone please share an example ?

CodeSandboX link https://codesandbox.io/s/gallant-water-5bmueq?file=/src/blogItem.js:0-1876

// App.js

import { BrowserRouter, Route, Routes, Switch } from "react-router-dom";
import Home from "./src/Home";
import BlogItem from "./src/blogItem";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/blogItem" element={<BlogItem />}></Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}
export default App;

//Home.js

import "./styles.css";
import React, { useState, useEffect, useCallback } from "react";
import BlogItem from "./blogItem";
const Home = (props) => {
  const [blogItem, setBlogItem] = useState(props);

  useEffect(() => {
    setBlogItem(props);
  }, [props]);

  return (
    <div id="App">
      <BlogItem />
    </div>
  );
};

export default Home;
  
// BlogItem.js 

import "./styles.css";
import React, { useState, useEffect, useCallback } from "react";

const blogData = [
  {
    id: 1,
    date: "25 Jan 2023",
    photo: "https://picsum.photos/80",
    heading: "Cypress setup blog",
    blogDetails:
      "Best heading added here. The most relevant data added here. Greatest of all time. Wont be a good idea play here always."
  },
  {
    id: 2,
    date: "22 Jan 2022",
    photo: "https://picsum.photos/80",
    heading: "React state details",
    blogDetails:
      "Best heading added here. The most relevant data added here. Greatest of all time. Wont be a good idea play here always."
  }
];

const BlogItem = ({ id, date, photo, heading, blogDetails }) => {
  const [searchResults, setSearchResults] = useState(blogData);

  const [state, setState] = useState({ id, date, photo, heading, blogDetails });

  const Columns = () => (
    <div className="blogItems">
      <div className="row">
        <div className="blogArea">
          {searchResults.map(({ id, date, photo, heading, blogDetails }) => (
            <a key={id}>
              <div className="blogImageSection">
                <img alt="id" src={photo} />
                <div key={id} className="dataArea">
                  <span className="dataDate">{date}</span>
                  <span className="tags">cypress</span>
                  <h3>{heading}</h3>
                  <p>
                    Best heading added here. The most relevant data added here.
                    Greatest of all time. Wont be a good idea play here always.
                  </p>
                  <a href="_blank" className="readmoreLink">
                    Read more →
                  </a>
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
  return <Columns {...state} />;
};

export default BlogItem;

// BlogDetails.js

import React from "react";

const BlogDetails = () => {
  return (
    <div id="App">
      <div className="blogDetailsSection">
        <div className="row">
          <div className="individual-blogs">
            <h2>ddd</h2>
            <p>Blog details</p>
            <pre>
              <code>const data = []; data.push("soccer");</code>
            </pre>
          </div>
        </div>
      </div>
    </div>
  );
};

export default BlogDetails;

CodePudding user response:

First of all make the browserRouter in the index.js file and remove it from the app.js file and create a Route for the BlogDetails component :

<BrowserRouter>
  <Routes>
      <Route path="/" element={<Home />}></Route>
      <Route path="/blogItem" element={<BlogItem />}></Route>
      <Route path="/blogDetails" element={<BlogDetails />}></Route>
   </Routes>
</BrowserRouter>

Then you have to install 'react-router-dom' package.

npm i react-router-dom

In BlogItem.js file import useNavigate from it :

import { useNavigate } from "react-router-dom";
const navigate = useNavigate(); // from inside the function component

Now you add onClick to the element that you want to click on it to be redirect to /blogDetails for example here :

<div className="blogImageSection"
onClick={() =>
  navigate('blogDetails', { state: {id, date, photo, heading, blogDetails } }) // this is how to pass data with useNavigate
}> ... </div>

Finally in BlogDetails.js file :

import { useLocation } from "react-router-dom";
const location = useLocation(); // from inside the function component

And you can access the passed data like this :

const myRecievedData = location.state
  • Related