0

When I read the ReactJS documentation it recommends using state to create controlled components. However, the below uncontrolled code is much cleaner and works flawlessly. I can understand why the parent component should use state, but the below code is so clean that I don't understand why controlled components are recommended. The "MyModule" prefix is optional and I don't even have to include that.

module MyModule {
   export let userName: string = "";

   interface iProps {
      userName?: string;
   }

   export class Build extends React.Component<iProps, {}> {
      constructor(props: iProps) {
         super(props);

         if (props.userName) {
            MyModule.userName = props.userName;
         }
      }

      handleChange(event) {
         MyModule.userName = event.target.value;
      }

      render() {
         return (<input type="text" defaultValue={MyModule.userName} onChange={this.handleChange.bind(this)} /> );
      }
   } //end class.
} //end module.
Lambert
  • 2,233
  • 5
  • 29
  • 44
  • Possible duplicate of [Controlled vs uncontrolled components ReactJs](https://stackoverflow.com/questions/44471370/controlled-vs-uncontrolled-components-reactjs) – Ozzy Walsh Sep 01 '18 at 17:09
  • 1
    it won't work if you have multiple instances of `Build` component in your app, because each instance will modify the same `userName` variable – Olivier Boissé Sep 01 '18 at 19:41
  • @OzzyWalsh - The accepted answer on the other post does not really apply to this code because this code is using a module level variable so it's value is available throughout the component. – Lambert Sep 01 '18 at 19:52
  • @OlivierBoissé - All of my components use the same "Build" class and work perfectly because they are encapsulated with different typescript module names. – Lambert Sep 01 '18 at 19:57
  • hum ,do you have multiple instances `Build` component on the same page ? I don't see the relation with having different module names – Olivier Boissé Sep 01 '18 at 22:03

2 Answers2

1

It works because the value that handleChange(event) is updating is stored outside the component class.

So basically it works when you have only one instance of Build component in your entire application. When you have multiple instances of the same component you probably want to make sure that each instance has its own value for userName. You could create multiple variables and associate each one somehow with each component instance, but using component state, or application-wide state store like redux are better ways to do that.

artem
  • 46,476
  • 8
  • 74
  • 78
0

The inputs will display the right value because they are uncontrolled. But all the js instances on the same page will have the same username. Also you will loose the "reactive" part of javascript. E.G. If you add a label to the input which would display username from input box it won't update on change.

T.Chmelevskij
  • 1,904
  • 17
  • 30