Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Parent function with useState Hook in React?

The ideal result is displaying strings when items in the list are clicked.

Here's the Root Component.

const App = () => {
  const [click, setClick] = useState(null);
  const handleClick = name => {
    setClick(name);
  };
  return (
    <div>
      <Parent handleClick={handleClick} />
      {click && <p>{click} is clicked.</p>}
    </div>
  );
};

and Parent Component.

const Parent = ({ handleClick }) => (
  <div>
    <Child
      name="First Item"
      handleClick={handleClick("First Item is Clicked!")}
    />
    <Child
      name="Second Item"
      handleClick={handleClick("Second Item is Clicked!")}
    />
    <Child
      name="Third Item"
      handleClick={handleClick("Third Item is Clicked!")}
    />
  </div>
);

and Child Component.

const Child = ({ name, handleClick }) => <li onClick={handleClick}>{name}</li>;

Also, the code sandbox link.

I just wondered why the result never is never changed by click.

like image 911
SPG Avatar asked Oct 17 '25 19:10

SPG


1 Answers

Problem is that you aren't passing a function to handleClick instead an evaluated value from parent. You code must be

import React from "react";
import Child from "./Child";

const Parent = ({ handleClick }) => (
  <div>
    <Child
      name="First Item"
      handleClick={() => handleClick("First Item is Clicked!")}
    />
    <Child
      name="Second Item"
      handleClick={() => handleClick("Second Item is Clicked!")}
    />
    <Child
      name="Third Item"
      handleClick={() => handleClick("Third Item is Clicked!")}
    />
  </div>
);

export default Parent;

Working demo

like image 74
Shubham Khatri Avatar answered Oct 19 '25 12:10

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!