· 2 min read

How to Reset and Clear a Form Field or Textarea with Stateless Components in React

Stateless components are nice. They are simple to use and understand but can become tricky when you start thinking about data and how to manage state. In general, the consensus seems to be that if your UI is going to need state, then at least the component that needs to be dynamic, should NOT be a stateless component. But after playing around and trying to build an entire app out of stateless components, it seems not only possible but perhaps preferable. To accomplish a dynamic UI with "state" like features, the trick is to attach the ReactDOM.render method to a callback on the window. Calling this method from anywhere in your app will trigger re-rendering the UI and give your UI that "stateful" feeling. Here is some code that demonstrates. window.render = () => { // calling window.render() anywhere in your components will redraw the UI w/new or updated state ReactDOM.render(, document.getElementById('root')); } const App = () => { form = { } // simple container for form fields update = (e) => { form[e.target.name] = e.target // we'll attach the target in the form obj here so we can reference it later } submit = (e) => { let value = form["fullname"].value console.log(value) form["fullname"].value = "" // reset the value of the "fullname" text input window.render() // redraw UI here } return (

Enter Your FullnameSubmit ) } window.render() That's really all there is to it!

Comments

Leave a comment