How to set state with dynamic key-value pair in React

With a dynamic key-value array you can save all form values without needing to create a separate variable for each form element.

import React, { useEffect, useState } from 'react'

const Form = props => {
	const [state, setState] = React.useState({});
	function handleFieldChange(event) {
		setState({ ...state, [event.target.name]: event.target.value });
	}
    return (  
	<div className="form">
            <div className="row g-3 mb-3">
                <div className="col">
                    <input name="firstname" onChange={handleFieldChange} />
                </div>
                <div className="col">
                    <input name="email" onChange={handleFieldChange} />
                </div>
            </div>
            <div className="row g-3 mb-3">
                    <div className="col">
                        <textarea name="message" onChange={handleFieldChange}></textarea>
                </div>
            </div>
        </div>
    );  
}
export default Form

Leave a Reply

Your email address will not be published. Required fields are marked *