Skip to content

Instantly share code, notes, and snippets.

@Anmo
Created July 22, 2020 08:58
Show Gist options
  • Save Anmo/0666e0dd5bc59ec90a838c5f7ffeef6d to your computer and use it in GitHub Desktop.
Save Anmo/0666e0dd5bc59ec90a838c5f7ffeef6d to your computer and use it in GitHub Desktop.
Creating one event handler for all input types in React by Akash Thakur
import React, { useState, useCallback } from 'react';
import useForm from './use-form';
import './styles.css';
export default function App() {
const [state, handleChange] = useForm({
userName: '',
age: '',
status: 'beginner',
comments: '',
color: 'red',
hasFootball: true
});
const formDataHandler = event => {
event.preventDefault();
console.log(state);
};
return (
<form>
<div className='inputs'>
<label>Name</label>
<input
type='text'
value={state.userName}
name='userName'
onChange={handleChange}
/>
</div>
<div className='inputs'>
<label>Age</label>
<input
type='number'
name='age'
value={state.age}
onChange={handleChange}
/>
</div>
<div className='inputs'>
<label>Level</label>
<div className='radio'>
<label>
Beginner
<input
type='radio'
name='status'
value='beginner'
checked={state.status === 'beginner'}
onChange={handleChange}
/>
</label>
<label>
Intermediate
<input
type='radio'
name='status'
value='intermediate'
checked={state.status === 'intermediate'}
onChange={handleChange}
/>
</label>
</div>
</div>
<div className='inputs'>
<label>Comments</label>
<textarea
name='comments'
value={state.comments}
onChange={handleChange}
/>
</div>
<div className='inputs'>
<label>Color</label>
<select name='color' onChange={handleChange} value={state.color}>
<option value='red'>Red</option>
<option value='orange'>Orange</option>
<option value='yellow'>Yellow</option>
</select>
</div>
<div className='inputs'>
<label>Football</label>
<input
type='checkbox'
name='hasFootball'
checked={state.hasFootball}
onChange={handleChange}
/>
</div>
<button onClick={formDataHandler}>Show form data in console</button>
</form>
);
}
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootElement = document.getElementById('root');
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
import { useState, useCallback } from 'react';
export default function useForm(initialState = {}) {
const [state, setState] = useState(initialState);
const updateState = useCallback((newState = {}) => {
setState({
...state,
...newState
});
}, [state]);
const handleChange = useCallback((event) => {
const value =
event.target.type === "checkbox"
? event.target.checked
: event.target.value;
updateState({
[event.target.name]: value
});
}, [updateState]);
return [state, handleChange, updateState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment