Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the state on the same page when clicked Submit button in react

I have made a form in react which takes input from the user and stores it in the state. Now, I want to display the state values when the user clicks Submit button in an input field just below the submit button in React. Im new to react.

like image 439
user8306074 Avatar asked Oct 19 '25 12:10

user8306074


1 Answers

You have to make an object (E.g. Credentials) and when someone clicks the button, credential takes the props of the state like this:

App.js

//import code....
import Form from './Form.js'

//class app code.....

//in the render method:

render() {
    return (
        <Form />
    )
}

Form.js

// import code ....
state = {
   firstName: '', // or what you want
   lastName: '', // or what you want
   email: '', // or what you want
   send: false,
}

//handleChange function
const handleChange = (event) => {
    const {name, value} = event.target
    this.setState({
        [name]: value
    })
}

//handleClick function
const handleClick = () => {
    this.setState({send: true})
}

In the Render method

render() {
    return (
        <div>
            <input name='firstName' onChange={handleChange} />
            <input name='lastName' onChange={handleChange} />
            <input name='email' onChange={handleChange}/>
            <button onClick={handleClick}>Send</button>

            {send && 
                <Credentials 
                    firstName={this.state.firstName} 
                    lastName={this.state.lastName} 
                    email={this.state.email} 
                />
            }
        </div>
    )
}

export default Form // or your file's name

In the Credential.js

//import code...

const Credentials = ({firstName, lastName, email}) => {
    return (
        <h2>firstName is: {firstName}</h2>
        <h4>lastName is: {lastName}</h4>
        <p>email is: {email}</p>
    )
}

export default Credentials
like image 91
Matteo Pagani Avatar answered Oct 22 '25 06:10

Matteo Pagani



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!