Why I cant share info between form input (child component) and React useState Hook (parent component)?

Asked
Active3 hr before
Viewed126 times

8 Answers

componentusestateinputreact
90%

I am doing a multiple step form with React and I expect that when the user hits "Next" button, he/she can go to the next form, save info in parent component useState Hook and keep it in the input if user decides to go back. Switch has 8 cases but I left only 1 for simplicity. Structure looks something like this (Questions after code):,1) When I write something on fullName input (UserInfo.js), I think React is updating the component with the default value ("") so I cant write anything on it. Expected behavior: User can write and input should be saved in datos.fullName on parent component. When user press Next or back, written information will still be there.,2) Is my approach OK? Should I be saving all children data in parent component and then access it from another child later on (Like Confirm.js or somewhere where the user can read the information before send it). I tried to learn Context API but still don't understand how to implement it 😅

Change your handleChange function like this:

  const handleChange = (e) => {
     const fieldName = e.target.name;
     const fieldValue = e.target.value;
     setDatos(prevDatos => ({
        ...prevDatos,
        [fieldName]: fieldValue
     }));
  };
88%

Employee Component is the Parent component and the Salary Component will be used as child component.,That means we want to pass the data from Employee component to the Salary component and from Salary Component back to Employee Component.,Lets assume that our application is having two components. One is Employee Component and the other one is Salary Component. It looks like below image.

Save the changes. Navigate to the browser. We can see that If we enter Salary in Employee Component, it gets updated in Salary Component and if we change it Salary Component, it gets updated into Employee Component. 

import ReactDOM from "react-dom";
import React, { Component, useState } from "react";

function NewEmployee(){

  const [employee,setEmployeeData]=useState({Id:'',Name:'',Location:'',Salary:''});    

  function changeEmployeeInfo(e){

    console.log(e);

    setEmployeeData({...employee,[e.target.name]:e.target.value});

  }

  return(

    <div>

      <h2>Welcome to Employee Component...</h2>

      <p>

        <label>Employee ID :

                <input type="text" name="Id" value={employee.Id}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Name : 

                <input type="text" name="Name" value={employee.Name} 

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Location :

                <input type="text" name="Location" value={employee.Location}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Salary : 

                <input type="text" name="Salary" value={employee.Salary}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        Employee ID is : <b>{employee.Id}</b>, Name is : <b>{employee.Name}</b> ,

         Location is : <b>{employee.Location}</b> and Salary is : <b>{employee.Salary}</b>

      </p>

      <SalaryComponent onSalaryChange={changeEmployeeInfo} salary={employee.Salary}></SalaryComponent>

    </div>

  )

}

const SalaryComponent=({onSalaryChange,salary})=>{

  function changeSalary(e){

    onSalaryChange(e);

  }

  return(

    <div style={{border:'3px solid red', width:'500px'}}>

      <h2>Welcome to Salary Component</h2>

    <p>

        <label>Employee Salary : 

                <input type="text" name="Salary" value={salary}

                onChange={changeSalary}></input>

        </label>

      </p>

    </div>
  );

}

const element=<NewEmployee></NewEmployee>

ReactDOM.render(element,document.getElementById("root"));
72%

Hi, I have a problem when trying to update the parent state via child component in a functional component.,I tried this solution, but it only works on the first invocation in my child component.,have the child own the state - so that only it updates (not the whole parent)

class Parent extends React.Component {
  state = { value: "" }

  handleChange = (newValue) => {
    this.props.setState({ value: newValue });
  }
  
  render() {
    // We pass a callback to MyInput
    return <MyInput value={this.state.value} onChange={this.handleChange} />
  }
}

class MyInput extends React.Component {
   handleChange = (event) => {
    // Here, we invoke the callback with the new value
    this.props.onChange(event.target.value);
  }

  render() {
	return <input value={this.props.value} onChange={this.handleChange} />
  }
}
load more v
65%

“However, we recommend to split state into multiple state variables based on which values tend to change together.”,In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.,Take the following React.js component tree architecture into account as an example:

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

Communication between Parent-Child Components in Vue Js ,On the above codes, we have created function handleChange that will pass the value through props.onChange to our Parent component., 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.

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%

In React data is passed top-down from one component to another through props.,Building a music player is a fantastic example to demonstrate how the useContext Hook works because it has two child components that share the same application state:,The React Context API allows you to easily access data at different levels of the component tree, without having to pass data down through props.

import AppContext from './appContext.js';

class Example extends React.Component {
   static context = AppContext;
   render() {
      let value = this.context;
      ...
   }
}
load more v
22%

Send data from the child component using the callback. , Pass this callback as a prop to the child component. , Create a callback in the parent component which takes in the data needed as a parameter.

const text = React.createElement('p', {}, 'This is a text');
const container = React.createElement('div', '{}', text);
ReactDOM.render(container, rootElement);
load more v
60%

If the Calculator owns the shared state, it becomes the “source of truth” for the current temperature in both inputs. It can instruct them both to have values that are consistent with each other. Since the props of both TemperatureInput components are coming from the same parent Calculator component, the two inputs will always be in sync.,We can start by extracting a TemperatureInput component from Calculator. We will add a new scale prop to it that can either be "c" or "f":,In React, this is usually solved by making a component “controlled”. Just like the DOM <input> accepts both a value and an onChange prop, so can the custom TemperatureInput accept both temperature and onTemperatureChange props from its parent Calculator.

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;  }
  return <p>The water would not boil.</p>;}
load more v

Other "component-usestate" queries related to "Why I cant share info between form input (child component) and React useState Hook (parent component)?"