Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sending props to components on separate pages

./Components/Categories.jsx

import CategoryData from "../mocks/categories.json"
import Products from './Products'

function Categories() {
  return  CategoryData.map((cat)=> <li onClick={ ()=> <Products id={cat.id} /> }> </li>) 

}

./Components/Products.jsx

function Products(props) {
    console.log(props.id)
}

I need to send props to another component in OnClick. but the code I wrote didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Hi there you are doing one thing wrong.
We cann’t render a component within an event handler.

You can do this like :

import React, { useState } from "react";
import CategoryData from "../mocks/categories.json";
import Products from "./Products";

function Categories() {
  const [categroy, setCategroy] = useState(null);

  const clickCategory = (cat) => {
    setCategroy(cat);
  };

  return (
    <ul>
      {CategoryData.map((cat) => (
        <li key={cat.id} onClick={() => clickCategory(cat)}>
          {cat.name}
        </li>
      ))}
      {categroy && <Products id={categroy.id} />}
    </ul>
  );
}

export default Categories;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading