React hooks: change state in parent function inside onClick function inside child function

Asked
Active3 hr before
Viewed126 times

9 Answers

onclickfunctionhooksstatereact
90%

First off, let me express that this is generally not the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: dispatch).,The other advantage to this solution is that you can add a lot more functions in the parent and child while passing them from the parent to the child using only a single property.,Callback-style refs are another approach to achieving this, although not quite as common in modern React:

const { forwardRef, useRef, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

  // The component instance will be extended
  // with whatever you return from the callback passed
  // as the second argument
  useImperativeHandle(ref, () => ({

    getAlert() {
      alert("getAlert from Child");
    }

  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>
load more v
88%

So let us create a parent component first So we have created a component with a button to call the child function later on.,For calling Child Component function from parent component in hooks we are using React.forwardRef and React.useImperativeHandle hooks from React. Now let us know briefly about these two. What are they? How are they used? And the most important question, how are we going to use them? So let’s get started!,Child component is rendered and a ref is created using React.useRef named childRef. The button we created in parent component is now used to call the child component function childRef.current.showAlert();

Arguments and return type: React calls this function with two arguments one is props and the other is ref. This returns a react node something like this.

const someComponent = React.forwardRef((props,ref)=>(    <div ref={ref} className="title">        {props.title}    </div>))
load more v
72%

Search Answer Titles

Pretag
 Pretag team - issue, fix, solve, resolve
65%

ourcodeworld.com is using a security service for protection against online attacks. This process is automatic. You will be redirected once the validation is complete. , ourcodeworld.com is using a security service for protection against online attacks. The service requires full cookie support in order to view this website. , ourcodeworld.com is using a security service for protection against online attacks. The service requires full JavaScript support in order to view this website.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component., Change Parent Component State from Child using hooks in React,As you see that we set the onChange property to the Child component. Next step is to create the Child component.

Child component holds the Input field and we are going to send the input field value to the Parent component. So let’s create the Parent component first.

function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // We pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}
load more v
40%

this in doStuff will refer to the calling component Child unless you doStuff={doStuff.bind(this)} when you call Child in the render function of Thing.,Today I find next solution I need to get my component wrapped with a function (because it receives url from routing functionality) Child component looks like this,So define the method on the parent, pass it to the child as prop and call it in the child;

import s from './Child.css';

class Child extends Component {
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1 ref="hello">Hello</h1>
  );
 }
}

export default withStyles(s)(Child);
load more v
22%

To achieve user interactivity, we can call functions and methods to accomplish specific operations in React. We pass data from parent to child or child to parent components using these actions.,Pass Data from Child to Parent using Referenced Action,Components are an integral part of React. Each React application consists of several components, and each component may require user interaction that triggers various actions.

1<ChildComponent
2    // The child component will access using actionName
3    actionName={this.actual_action_name}
4/>
load more v
60%

Step 2: Use ref in Child component,Step 1: Create Reference Variable,Step 3: Enclose Child component in React.forwardRef function.

export default class Parent extends React.Component{
  state = {
    name: 'Thor',
    home: 'Asgard',
  };

  render(){
    return(
      <div>
          <p>
              Change Parent State - <br />
              Name: <input type={'text'} value={this.state.name} onChange={(e) => this.setState({name: e.target.value})} />
              home: <input type={'text'} value={this.state.home} onChange={(e) => this.setState({home: e.target.value})} />
           </p>
           <Child parentState={this.state} />
      </div>
    )
  }
}

class Child extends React.Component{
  state = {
    brother: 'Loki',
    job: 'Being Awesome',
  }
  render(){
    return (
       <div>
           <p>
              Change Child State - <br />
              Brother: <input type={'text'} value={this.state.brother} onChange={(e) => this.setState({brother: e.target.value})} />
              Job: <input type={'text'} value={this.state.job} onChange={(e) => this.setState({job: e.target.value})} />
           </p>
           <p>
               (Parent State Passed to Child) <br />
               Name: {this.props.parentState.name} <br />
               Home: {this.props.parentState.home}
           </p>
           <p>
               (Child State) <br />
               Brother: {this.state.brother} <br />
               Job: {this.state.job}
           </p>
       </div>
    )
  }
}
load more v
48%

And there we have it! A simple webapp authentication demo that passes data from child to parent component via functions!,However community contributions to the documentation may re-introduce the notion of the "creational parent":,Built on Forem — the open source software that powers DEV and other inclusive communities.

const App = () => {
  const [user, setUser] = useState(null);

  return user ? <AuthWebsite/> : <NoAuthWebsite/>
};
load more v

Other "onclick-function" queries related to "React hooks: change state in parent function inside onClick function inside child function"