1

I want to make a generic input component using hooks but not 100% sure how to implement this.

So I have a parent component

const Parent = () => {
   const [team, setTeam] = useState('');
   return <Input onChange={???} value={team} />
} 

and then my Input component looks like this.

const Input = ({onChange}) => {
   return <input onChange={onChange} />
}

I am wondering where the state should be stored. Is it in the Parent component, or in the Input or do both need to store state?

4
  • Why do you insist on using hooks? A class component would make it much easier Commented Feb 14, 2019 at 18:00
  • Why do you insist on using a class component ? A hook would make it much easier @DorShinar Commented Feb 14, 2019 at 18:50
  • Because you can't bind functions in a functional component. The performance benefit from not binding might be negligible in some cases, but in other it could slow the application. Commented Feb 14, 2019 at 18:54
  • @DorShinar because I'm riding on the HOOKS hype train 😎, don't get left behind brother 😁 Commented Feb 14, 2019 at 23:13

1 Answer 1

4

Simply use an arrow function bound to your onChange event. Then use the setTeam callback given in your hook inside of it :

const Parent = () => {
    const [team, setTeam] = useState('');
    return <Input onChange={ev => setTeam(ev.target.value)} value={team} />
}

Also, avoid having redundant state values. Any information should only be stored in the component it is used in.

The shortened Input code :

const Input = ({ onChange, value }) => <input onChange={onChange} value={value} />

Or :

const Input = props => <input {...props} />
Sign up to request clarification or add additional context in comments.

6 Comments

If the parent component will be rendered often, creating the callbacks over and over again could impact performance
and is input just const Input = () => (<input />);
I am seeing the following error: Failed prop type: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly.
It seems that the function you passed is undefined
It's generally not a good idea to use arrow functions in onChange to bind callbacks. A better way is to bind in the constructor or directly on the class field.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.