Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing onChange event from child to parent in React

I want to pass the onChange from child to parent. I don't even know if that is the correct way of putting it. But here is my code. The code worked previously but I am trying to break down my code into smaller components and dealing with the errors. If you would like more code, I am happy to share. I am a bit new to React. I don't know what I am doing wrong. The error is basically that the function which takes the event isn't getting anything.

Parent:

        <Inputs hasInputs={hasInputs} onSubmit={this.handleSubmit} thoughtProp={this.state.thought} onChange={this.handleChange} />

Child:

import React from 'react'
import { Input } from '../Input.js'

export const Inputs = (props) => {
    return (
    <form className="flex-item-main form" onSubmit={props.onSubmit}>
        <ol>
            {props.thoughtProp.map((input, index) => (
            <Input type='text' onSubmit={props.onSubmit} key={index} value={input} onChange={(event) => props.onChange(event, index) } className='textInputs' />
            ))}
            { props.hasInputs ? (
            <input className='submitThoughts' type='submit' value='Submit Thought!' />
            ) : (
            null
            )}
        </ol>
    </form>
    )
}
like image 352
Andrew Lovato Avatar asked Feb 01 '26 05:02

Andrew Lovato


1 Answers

Change Parent Component State from Child using hooks in React

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.

Parent.js

import Child from "./Child";
   function Parent() {
        const [name, setName] = useState("");
        const [password, setPassword] = useState("");
    
        const onChangeName=(newValue)=>{
          setName(newValue);
        }
    
        const onChangePassword=(value)=>{
          setPassword(value);
        }
        // We pass a callback to Child
        return (
       <Child  onChangeName={onChangeName} onChangePassword={onChangePassword} />;
    )}

As you see that we set the onChange property to the Child component. Next step is to create the Child component.

Child.js

    function Child(props) {
           
 return(
 <input  onChange={(e)=>{props.onChangeName(e.target.value)}} />
 <input  onChange={(e)=>{props.onChangePassword(e.target.value)}} />
       )}

On the above codes, we have created function handleChange that will pass the value through props.onChange to our Parent component.

like image 188
soma iyappan Avatar answered Feb 02 '26 17:02

soma iyappan



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!