React child to parent communication - part 10

←React Forms and Controlled Component : input, select - part 9

React tutorial - pass data from child to parent functional component - elpeeda.net


Because data is transferred in a single flow, throughout our application, we have been using props to pass data from the parent to child component.

However, what if we have data that was saved in a child component and we need to transfer it to its parent component? React does not allow us to transfer props from child to parent, so you might start at the bottom with a child component and progressively work your way up.

When we split the component, there needs to be a link between them so they may communicate with each other. Props enable us to accomplish this, but in this instance,  when the parent component has to obtain data from the child, We can communicate from child to parent similarly but in a different manner.

Let's follow these three simple steps-

  • We create a function in the parent component and this function helps to retrieve data from the child component.

  • In JSX, We declare props as an event to the child and pass a handler function as a value which allows us to pass a function from the parent to the child component.

  • We call the function inside the child component and that function accepts an argument that contains data from the child component.
It also meant "lifting state up," where "state" refers to data, which can be in the form of a const, function, variable, string, or object.

In the last portion where we covered form handling and submission, and where we also alerted our submission data. App.js is the parent component, and UserForm.js is the child component; the child component has a form that can be submitted to send data to the parent component.


import './UserForm.css'
import {useState} from 'react'
const UserForm = (props) => {
  const [name, setName] = useState('')
  const [language, setLanguage] = useState('')
  const [level, setLevel] = useState('beginner')

  const nameChangeHandler = (e) => {
    setName(e.target.value)
  }
  const languageChangeHandler = (e) => {
    setLanguage(e.target.value)
  }
  const levelChangeHandler = (e) => {
    setLevel(e.target.value)
  }
  const submitFormHandler = (e) => {
    e.preventDefault()

    const userDetail = {
      name: name,
      language: language,
      level: level
    }
    alert(`${name} ${level} ${language}`)
  
    setName('')
    setLanguage('')
    setLanguage('')
  }
  return (
    <form onSubmit={submitFormHandler}>
      <div className="form-control">
        <label for='name'>Name</label>
        <input value={name} type='text' id='name' onChange={nameChangeHandler} />
      </div>
      <div className="form-control">
        <label for='language'>Language</label>
        <input value={language} type='text' id='language' onChange={languageChangeHandler} />
      </div>
      <div className="form-control">
        <label for='level'>Choose a Level</label>
        <select value={level} id='level' onChange={levelChangeHandler}>
          <option value='beginner'>Beginner</option>
          <option value='medium'>Medium</option>
          <option value='advance'>Advance</option>
        </select>
      </div>
      <div className="form-control">
        <button className="form-btn" type="submit">submit</button>
      </div>
    </form>
  )
}
export default UserForm

Now, in JSX, we can build event-like properties that begin with the on keyword and have the name "onAddDetail"; its value will be the function "addDetailHandler"; note that there should be no parenthesis after the function name because it is a pointer that will be activated when something occurs.

const App = () => {
 const addDetailHandler = (newUserDetail) => {
  
  alert(`${newUserDetail.name} ${newUserDetail.language} ${newUserDetail.level}`)
 }
 return (
  <div className="App">
   <UserForm onAddDetail={addDetailHandler} />  
  </div>
 )
}


Pass the onAddDetail function as a props in the UserForm function component, which is a child component. Use the (props) keyword or supply the function name explicitly inside curly braces, such as {onAddDetail}, and call the method inside the submitFormHandler with the userDetail parameter to pass data to the parent component.

/* props.onAddDetail(userDetail) */  
const UserForm = (props) => {
 const submitFormHandler = (e) => {
    e.preventDefault()

    const userDetail = {
      name: name,
      language: language,
      level: level
    }
    
    props.onAddDetail(userDetail)

    setName('')
    setLanguage('')
    setLanguage('')
  }
}


As you can see, when the callback method was called from within the child component, an alert was displayed with the information that had been sent to the parent component.

Conclusion

When a parent component sends data to a child component, it does so using props, but when a child component sends data to a parent component, it involves a different process. In this case, the child component sends data to the parent component using a function that takes data from the child component as input.

 You can accept a function via props and call it from within the child component, as well as a reference to the function that should be called when the event occurs, to have the parent component perform an action.

0 Comments:

Post a Comment