I want to create a web-app coding game with react that involves evaluating some user (javascript) input.
constructor(props) {
super(props);
this.state = {
code: ''
};
}
handleChange(key) {
return event => this.setState({ [key]: event.target.value });
}
funScript() {
eval(this.state.code);
}
anotherScript() {
console.log("Will this work?");
}
render() {
return (
<div>
<input
type={"text"}
value={this.state.code}
onChange={this.handleChange('code')}
/>
<button onClick={this.funScript()} >run</button>
</div>
);
}
I was hoping that the text input would be able to evaluate javascript on button press by the user (the user types in this.anotherScript(); and the console logs "Will this work?". Unfortunately, it doesn't work and I suspect its an issue specific to React. As soon as the input box is typed in, it tries to evaluate the string (without the button even being pressed!). See here for an example: https://codesandbox.io/s/54rkp584ll
Anyone have a proper React solution that doesn't break javascript on the first character input (and evaluates the function)?