Can we set a placeholder value for the input field?

Question

In the context of this exercise, can we set a placeholder value for the input field?

Answer

Yes, there are a few ways you can do this. The first method was covered in the previous exercise, which is done by setting an initial value to the state. This method places some actual text in the field, so a user would have to edit it. For instance,

this.state = { userInput: 'Some initial text' };

Another method is to utilize the input HTML element’s attribute placeholder, which sets some placeholder text in the field, but unlike the previous method, it will not be an actual value. It can be done like so, by adding the parameter,

<input placeholder="placeholder text" />

6 Likes

what is point of adding this to ?

value={this.state.userInput}

if I delete it , nothing change or happen different .

5 Likes

If you do that, you need to alter the onChange of the element to update this.state.userInput with the new value. This is called a controlled component because you are controlling the state of the element not letting it do the normal thing of handling it’s own statem

1 Like

Isn’t that what our handleUserInput() function is doing? When it is called it is calling this.setState() to set the userInput state value to the current value of the input field.

With out looking at it, yes it sounds like it is. That said, it appears I misread the original post I was replying to. However, it is still to do with controlled components. My answer should have been more like:

By removing value={this.state.userInput it may appear like nothing has changed but where and how the value is being controlled has changed. Without looking at the code I can’t say what you’d expect the difference to be. Given it is just an example it may be at this stage there is no difference functionally. But if you was to start sharing state or changing it else where you would notice a difference in behaviour.

3 Likes

Lets say you want to use the value somewhere else , then you can use the value from this attribute .

2 Likes

@script4129444325 I think the main use of :

becomes apparent when we have a text that should be a place holder, that is our initial userInput state is not an empty string.

for example

this.state = {
userInput: "my name is "
}
without :

Our input field would be empty, the value would be the default empty " ",
but our this.state.userInput would be "my name is " and this means that our
h1 tag {this.state.userInput} would render “my name is”!

Here’s a screenshot of what I’m describing

So the line setting the value = {this.state.userInput} can be omitted if we always intend to have our initial state as an empty string. But if we want the state to be anything other than an empty string it should be used.

2 Likes