Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamically a Hook in React?

Tags:

reactjs

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

like image 885
VersifiXion Avatar asked Jul 13 '26 08:07

VersifiXion


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

like image 107
Dupocas Avatar answered Jul 16 '26 05:07

Dupocas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!