alittlecurryhot
alittlecurryhot

Reputation: 487

unable to fetch/show input value

I am trying to update update user's name when the input field is filled and button is clicked using react (fairly new to react).

My Code so far.

class Header extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        userName: "Jhon Doe"
    }
}



updateUserName = (e) =>  {
    this.setState({
        userName: e.target.value
    })
}
render() {
    return(
    <div className = "header-section">
        <h2>Hello, {this.state.userName}.</h2>
        <input type="text" placeholder = "enter name to update" />
        <button className = "changeNameButton" onClick = {this.updateUserName}>Update Name</button>
    </div>
      )
   }
 }

 class App extends React.Component {
render() {
    return(
        <div>
            <Header />
        </div>
    )
      }
    }

  ReactDOM.render(<App />, root)

but when I click on the button it is not showing the updated name. Basically, I want to fetch the value of entered in the input. What's missing in my code?

Upvotes: 1

Views: 477

Answers (7)

Tikkes
Tikkes

Reputation: 4689

The onChange input has to be called on the name field. A shorter version of the already proposed solution would be using the latest version of react and make use of Hooks

const NameForm = () => {
  const [firstName, setFirstname] = useState('John Doe');

  function handleSubmit() {
    alert(`hello ${firstname}`);
  }

  return <form onSubmit={handleSubmit}>
      <input type="text" value={firstName} onChange={e => setFirstname(e.target.value);} />
    </form>
}

Upvotes: 0

0DDC0
0DDC0

Reputation: 5189

I see that you are taking your first steps to react. But you need to first understand what DOM events are in the WEB world and how they work. For now I have included a working sample for you to understand.

As you can see the typing on the text box triggers an event called "onChange". This is the event that contains the changes that we do to the text box. We should capture this as it happens as shown in a react state.

The click event on the button does not have this information. It has information relevant to the button. But we can update the data that we maintained in our react state "realTimeUpdatedUserName" and update it on another state variable. Then we can instruct react to bind this value to any ui element that needs to show it.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      realTimeUpdatedUserName:"",
      userName: "Jhon Doe"
    };
  }
  
  cacheUserNameUpdates = e => {
    this.setState({
      realTimeUpdatedUserName: e.target.value
    });
  }
  
  updateUserName = e => {
    this.setState({
      userName: this.state.realTimeUpdatedUserName
    });
  }
  
  render() {
    return (
      <div className="header-section">
        <h2>Hello, {this.state.userName}.</h2>
        <input value={this.state.realTimeUpdatedUserName} type="text" 
        placeholder="enter name to update" 
        onChange={this.cacheUserNameUpdates} />
        <span> Real time updates: {this.state.realTimeUpdatedUserName}</span>
        <br/>
        <button className="changeNameButton" onClick={this.updateUserName}>
          Update Name
        </button>
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
      </div>
    );
  }
}

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

Upvotes: 2

Ivan
Ivan

Reputation: 96

in react, there is 2 way to control the input, which is : controlled component, and uncontrolled component.

in controlled component, we detect every keypressed and update the state and display the value back into the text input, while in uncontrolled component, we reference the text input component and get the value as usuall ... for more explanation, you can read it here : https://reactjs.org/docs/forms.html it explains the forms and how we can handle the input value

as for your code : parameter 'e' in function updateUserName might refer to the button(because you put updateUserName in button) ... not to text input, so when u update the state, the value may be wrong.

Upvotes: 0

samrassp
samrassp

Reputation: 21

you can use onchange within input. then It call to set state.

      return(
      <div className = "header-section">
          <h2>Hello, {this.state.userName}.</h2>
          <input type="text" placeholder = "enter name to update"  onChange={this.updateUserName} />
          <button className = "changeNameButton" > Update Name</button>
      </div>
        )

Upvotes: 1

k1941996
k1941996

Reputation: 183

You need to store the value of the editText in a temporary variable if you want to do something with it.

The below code displays the following code which stores the data in temp state and onclick of the button updates the value of username.

class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userName: "Jhon Doe", temp: ""
    }
  }



  updateUserName = () => {
    this.setState({
      userName: this.state.temp
    })
  }
  changeTempName = (e) => {
    this.setState({
      temp: e.target.value
    })
  }
  render() {
    return (
      <div>
        <h2>Hello, {this.state.userName}.</h2>
        <input type="text" placeholder="enter name to update" onChange={(e) => this.changeTempName(e)} />
        <button className="changeNameButton" onClick={this.updateUserName}>Update Name</button>
      </div>
    )
  }
}
export default App;

Upvotes: 0

Hubi
Hubi

Reputation: 104

The reason is you have no onChange input. That's why the name is undefined. It should be a form element.

You can check ReactJS docs https://uk.reactjs.org/docs/forms.html

  class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Ім\'я, що було надіслано: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Ім'я:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Надіслати" />
      </form>
    );
  }
}

But you need to validate this form in future, So I recommend you to try Good form-validator

Upvotes: 1

RCZiegler
RCZiegler

Reputation: 41

Consider using onChange in input to call updateName, It will trigger state change in real-time. You could then get rid of the button. Right now the event coming into updateName is that of the button and not the input.

Upvotes: 0

Related Questions