This is a pretty common pattern in React components:
handleTextFieldChange(event) { const name = event.currentTarget.name; this.setState({[name]: event.currentTarget.value}) }
What Javascript syntax could be used to do the same with React hooks?
i.e. something possibly along the lines of:
handleTextFieldChange(event) { const name = event.currentTarget.name; this.set[name](event.currentTarget.value); }
Line 1: We import the useState Hook from React. It lets us keep local state in a function component. Line 4: Inside the Example component, we declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names.
There are many methods of managing state in React, including class-based state management and third-party libraries like Redux. In this tutorial, you’ll manage state on functional components using a method encouraged by the official React documentation: Hooks. Hooks are a broad set of tools that run custom functions when a component’s props change.
The names on the left aren’t a part of the React API. You can name your own state variables: This JavaScript syntax is called “array destructuring”. It means that we’re making two new variables fruit and setFruit, where fruit is set to the first value returned by useState, and setFruit is the second. It is equivalent to this code:
“Create” wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders, useState gives us the current state. Otherwise it wouldn’t be “state” at all! There’s also a reason why Hook names always start with use. We’ll learn why later in the Rules of Hooks.
How about something like this?
function handleTextFieldChange(mySetFunction, event) { const value = event.currentTarget.value; mySetFunction(value); } <TextField placeholder="Email" name="passwordResetEmailAddress" onChange={(e) => handleTextFieldChange(setPasswordResetEmailAddress, e)} > {passwordResetEmailAddress} </TextField>
I've tested it and it works.
You could use a single useState
with a default value of an object that contains all your input values and update that like you are used to with class components.
Example
const { useState } = React; function App() { const [state, setState] = useState({ email: "", password: "" }); function onChange(event) { const { name, value } = event.target; setState(prevState => ({ ...prevState, [name]: value })); } return ( <div> <input value={state.email} name="email" onChange={onChange} /> <input value={state.password} name="password" onChange={onChange} /> </div> ); } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With