Forms without refs in React stateless components
Hello there, there’s this silly thing I do with forms in my components and I want to share it with you. I always see people getting form values with refs, things you can’t use in stateless components. But it doesn’t matter, you can use something Javascript has already in itself : events !
If your component looks like this :
When the user submit the form, an event is sent with all you need :
To those who didn’t understand what’s going on : You get the value of the children you want from the submitted form and you rename them into proper name. Of course, if you can’t have a form in your component, you’re forced to use a ref and turn this component into a class.
That’s it, I know it feels kinda hacky but it works and I find it pretty elegant. Don’t hesitate to tell me your opinion about this. 😊