sam1024
sam1024

Reputation: 65

Change Parent Component State from Child functional component in React

I've created a signing page component which contain sign-in component and sign-up component. My problem is how do I pass a onClick function from parent to child so as to change the state of my parent component(signing page component)? What I expect is that by clicking the button from child components so that the active state of the parent can be toggled and the style can be changed based on the active state. I am trying to pass a handleClick function from parent to child but it does not work well.

Any solutions?

Details in codesandbox: https://codesandbox.io/s/wizardly-sanne-rf0u2?file=/src/components/SignIn/SignIn.js

In my parent component (SignPage),

function SignPage() {
  const [active, setActive] = useState(false);
  const handleClick = () => {
    setActive(!active);
  };

return (
    <div className="sign-container">
      <div
        className={active ? "sign-wrapper s-signup" : "sign-wrapper"}
      >
        <SignIn handleClick={handleClick} />
        <SignUp handleClick={handleClick} />
      </div>
    </div>
  );
}

In my child components (SignIn / SignUp)

import React, { useState } from "react";
import "./SignIn.css";

function SignIn(handleClick) {
  return (
    <div className="sign-in-container">
      <form className="sign-form sign-in">
        <h2>Sign In</h2>
        <label htmlFor="email">
          <span>Email Address</span>
          <input type="email" name="email" />
        </label>
        <label htmlFor="password">
          <span>Password</span>
          <input type="password" name="password" />
        </label>
        <button className="submit" type="submit">
          Sign In
        </button>

        <p className="panel-switcher" onClick={handleClick()}>
          Don't have an account?
        </p>
      </form>
    </div>
  );
}

export default SignIn;

Upvotes: 1

Views: 2201

Answers (2)

Won Gyo Seo
Won Gyo Seo

Reputation: 442

First, the props of component is object type.

So, if you wanna get the handleClick in child, it should be like below.

function SignIn({ handleClick }) {
  // ...
}

Second, when handling over a function to child, it should not be called.

for example, like below.

<p className="panel-switcher" onClick={handleClick}>

Upvotes: 1

ljbc1994
ljbc1994

Reputation: 2244

You're almost there, props are passed through as an object in the first parameter so for the SignIn component you can use destructuring so change to:

function SignIn({ handleClick }) {
   // code...
   // Remove the () from `handleClick()` as that will immediately execute the function.
   <p className="panel-switcher" onClick={handleClick}>
}

Upvotes: 1

Related Questions