Boyang
Boyang

Reputation: 2566

onChange event for textarea instead of get value when needed

I want to understand the performance implications of React's advocated way of handling textarea's value change.

Before React's one-direction data flow philosophy, one would do:

button.onClick( processInput(textarea.value) );

Now, one has to do

textarea.onChange( dispatch({ type: "inputChange", value: textarea.value }) );
button.onClick( dispatch({ type: "buttonClick" }) );

store(
    if (action.type === "inputChange") {
        this.lastInput = action.value
    } else if (action.type === "buttonClick") {
        processInput(this.lastInput)
    }
)

Is my understanding correct? Isn't this much more events compared to before? Why spam with many useless inputChange events? If my understanding is not right, what is the correct React way of doing this?

Upvotes: 0

Views: 1783

Answers (2)

markerikson
markerikson

Reputation: 67587

First, you're conflating a couple different things. React's "controlled input" pattern doesn't require Redux. You can implement controlled inputs inside a component, using local component state. I have a gist discussing this concept at react-controlled-inputs.md.

Second, even if you're using Redux, you don't have to directly control the input with Redux state and actions. Whether you do so is up to you. In fact, there are times when you might want to buffer text onChange events locally in the component, and only dispatch a Redux action once the user is done typing. I've got another gist demonstrating a buffering wrapper component at FormContentsContainer.jsx.

Finally, even if you do decide to directly control an input with Redux state, I'm not exactly sure why you're saying it's "more events". The input's onChange is going to fire every time you type, regardless. It's up to you whether you choose to do something with those events like translating them into Redux actions, or ignore them. Or, if you prefer to use "uncontrolled inputs" and just ask the inputs for their values when someone clicks Submit, that's entirely up to you as well.

Upvotes: 2

just-boris
just-boris

Reputation: 9776

I think it would be better to extract actual code from the Gist and put it here.

If you need text value only on button click, you can ask it through ref

const MyComponent extends Component {  
  onClick() {  
    const input = this.refs.myInput;  
    const value = input.value;  
    // do something with the value  
  }

  render() {
    return <input type="text" ref="myInput" />
  }
}

You can get access to DOM element inside of your component using refs. If you need some simple solution, that will work for you.

Upvotes: 0

Related Questions