Stephan - the curious
Stephan - the curious

Reputation: 423

How to build a multi-functional-component form with hooks in react?

I have one form App.js (parent) which renders two separate (child) components that build this form: Email.js and Button.js.

When the button is clicked, an alert should show the input collected.

The code below is as far as I get. Can someone help me to:

  1. complete the two components and
  2. connect them successfully into the Parent (App.js)?

I got this as an exercise where I was shown how this works with class components. I have difficulties to translate this into functional components with several children.

This is my App.js structure:

import React, { useState } from 'react';
import Button from './components/Button.js';
import Email from './components/Email.js';


function App() {

  return (
    <div>
      <form>
        <Email />
        <Button />
      </form>
    </div> 
  );
}

export default App;

My Email.js:

import React, { useState } from "react"

function Email() {

  const [input, inputChange] = useState({email: ""})

  const handleChange = (event) => {
    inputChange({[event.target.name]: event.target.value})
  } 

  return (
    <div className = "form-group">
        <label>Email adress </label>
        <input
            type="text"
            name="email"
            placeholder="Enter your email!"
            value = {input.email}
            onChange = {handleChange}
        />
    </div>
  )
}

export default Email

And my button:

import React, { useState} from "react"

function Button() {

    return (
        <div>
            <button onClick={handleClick}>Click me></button>
        </div>
    )

}

export default Button 

Upvotes: 1

Views: 1303

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31335

See if this works for you:

function App() {

  const [email,setEmail] = React.useState('[email protected]');
  
  function changeEmail(event) {
    setEmail(event.target.value);
  }
  
  function handleClick() {
    alert('The email entered was: ' + email);
  }

  return(
    <React.Fragment>
      <Email
        email={email}
        changeEmail={changeEmail}
      />
      <Button
        handleClick={handleClick}
      />
    </React.Fragment>
  );
}

function Email(props) {
  return(
    <input type='email' value={props.email} onChange={props.changeEmail}/>
  );
}

function Button(props) {
  return(
    <button onClick={props.handleClick}>Click</button>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Upvotes: 1

Related Questions