Written by Sean Behan on Sun Oct 21st 2018

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(<App/>, 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 (
    <div className="App">
      <label>Enter Your Fullname</label>
      <input type="text" name="fullname" onChange={update}/>
      <button onClick={submit}>Submit</button>
    </div>
  )
}

window.render()

That's really all there is to it!


Tagged with..
#react #functional #state #form fields #textarea #reactjs

Just finishing up brewing up some fresh ground comments...