React Hooks - How can I pass props from child to parent component

Viewed 453

I want to pass the form data from a child component to a parent component, so I can use them inside the parent component. But don't know how to do so.

Child component

import React, { useState } from 'react';

const InputForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
  };

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Form.Group>
          <Form.Control
            type='text'
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </Form.Group>

        <Form.Group>
          <Form.Control
            type='email'
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />

        <Button type='submit'>
          Submit
        </Button>
      </Form>
    </>
  );
};

export default InputForm;

Parent component

import React from 'react';
import InputForm from './InputForm';
    
const App = () => {
  return (
    <div className='App'>
        <InputForm />
        Name is {name}
        Email is {email}
    </div>
  );
};

export default App;
1 Answers

You got two options.You can either implement redux or something similar to decouple the state, or you can pass down a callback to you child to pass the form data back to your parent component

Related