7

on the homepage of React, there's the last example (A Component Using External Plugins) with a textarea:

    <textarea
      id="markdown-content"
      onChange={this.handleChange}
      defaultValue={this.state.value}
    />

As I type, the textarea gets updated.

Now, I tried to change defaultValue with value:

    <textarea
      id="markdown-content"
      onChange={this.handleChange}
      value={this.state.value}
    />

And the outcome is the same (as with defaultValue, i.e. as I type, the textarea gets updated visually with the updated text).

So, what is the real difference between the two?

tonix
  • 6,671
  • 13
  • 75
  • 136

3 Answers3

5

I think a good example for this is if you use a hard coded string

using defaultValue prop:

function App(){ 
  return(
    <textarea
      defaultValue="foo" // only by default foo
    />
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

using value prop

function App(){ 
  return(
    <textarea
      value="foo" // will forever be foo
    />
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

So while the snippet below this paragraph might look like it is the same as using value prop because of onChange potentially updating the state value (therefore it looks like it is updating defaultValue prop) - it is not. It is still an uncontrolled component and will update its value directly from the user input. It is simply initialized with the default value of whatever this.state.value is when it is initially rendered.

<textarea
  id="markdown-content"
  onChange={this.handleChange}
  defaultValue={this.state.value}
/>
95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
3

As long as you change the value that is used in value there won't be any difference. If you won't update the variable and have set a textareas value you can't change the value of the textarea by typing. By using a defaultValue you don't have to update any variable.

ChrKahl
  • 641
  • 5
  • 25
  • This means that ` – tonix May 06 '19 at 08:16
  • 1
    Right. To change the value with the `value={..}` property you need to assign a onChangeHandler. – ChrKahl May 06 '19 at 08:21
3

see demo image here

You can edit the input value without onchange event handler when you use default value with the input tag.

If you use value with input tag you need to use onchange event handler to make changes to input value.

Code sample

jayanth
  • 72
  • 4