How to create dynamically a Hook in React?

Viewed 4603

I know what I'm about to say may not be possible but I want to do something with functional components that I did in React with Class Components,

With Class Components, you can do this :

handleChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  });
}

The this.state."e.target.name" is created dynamically with the value of e.target.name,

but how in functional components (hooks), you set dynamically a hook according the value of the name of an input ?

It would be something like this (don't shout, I know that can't be done :D) :

function handleChange(e) {
  set`${e.target.name.toUpperCase()`(e.target.value);
}

I know there's 99% that you tell me "that's not possible" but I really wanted to be sure,

Thank you

1 Answers

This has nothing to do with hooks itself, it's more on how you're defining your state. You can reproduce the behavior you want using useState like this

const Component = () =>{
    const [state, setState] = useState({})

    const onChange = e =>{
        const { target: {value, name } } = e

        setState(prev =>({
            ...prev,
            [name] : value
        }))
    }

} 

Now if state[name] is undefined a new property is added, if state[name] is already defined the old value is overwrited

Related