Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  158] [ 5]  / answers: 1 / hits: 16933  / 5 Years ago, mon, march 4, 2019, 12:00:00

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 (
<div>
<input type=text onChange={ this.handleChange } />
<Button>Save</Button>
</div>
);
}
}

More From » reactjs

 Answers
16

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>

<input type=text onChange={ this.handleChange } />
<input
type=button
value=Alert the text input
onClick={this.handleClick}
/>
</div>
);
}
});

[#52485] Thursday, February 28, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carrington

Total Points: 674
Total Questions: 90
Total Answers: 108

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;