Bind input to state with Hooks

Last update in 8/2019

Used for every React form, binding input to state is must have in your React toolbox. Now with hooks, easier than ever.

First we need to import React and useState hook.

import React, { useState } from 'react'

After that we need to initialize state on top of functional component using useState hook.

const [input, setInput] = useState('')

All that's left to do is to create input element with value of state and onChange method which will update state on every input change.

<input type='text' value={input} onChange={e => setInput(e.target.value)} />

You can see how this works in demo.

Full example code for reference:

import React, { useState } from 'react'

const ExampleComponent = () => {
const [input, setInput] = useState('')
return (
<div>
<input
type='text'
value={input}
onChange={e => setInput(e.target.value)}
placeholder='type something'
/>
<h1>{input}</h1>
</div>
)
}

export default ExampleComponent

Resources #