Skip to content Skip to sidebar Skip to footer

Reactjs: Using Alert() To Take Input From User

How can I use alert() to allow the user to enter their name, and save it to state? Here is what I have attempted so far: render: function() { return (

Solution 1:

One option would be to use the prompt() function, which displays a modal dialog through which user input can be entered and acquired. The prompt() method also allows you to supply a custom greeting, which can be passed as the first argument like so:

const enteredName = prompt('Please enter your name')

Integrating this with your existing react component can be done in a number of ways - one approach might be as follows:

/* Definition of handleClick in component */
handleClick = (event) => {

    /* call prompt() with custom message to get user input from alert-like dialog */const enteredName = prompt('Please enter your name')

    /* update state of this component with data provided by user. store data
       in 'enteredName' state field. calling setState triggers a render of
       this component meaning the enteredName value will be visible via the
       updated render() function below */this.setState({ enteredName : enteredName })
}

render: function() {
    return (
      <div>

        {/* For demonstration purposes, this is how you can render data 
            previously entered by the user */ }
        <p>Previously entered user name: { this.state.enteredName }</p><inputtype="text"onChange={this.handleChange } /><inputtype="button"value="Alert the text input"onClick={this.handleClick}
        /></div>
    );
  }
});

Solution 2:

I think you mean prompt():

var userName = prompt('Please Enter your Name')

The userName variable will contain the user answer.

Post a Comment for "Reactjs: Using Alert() To Take Input From User"