sthig sthig - 1 year ago 54
Javascript Question

React handleSubmit return value to dom

I'm attempting to write a very basic MadLibs game to learn more about React.js, I'm running into an issue of where a user enters in a value (a name) and then

handleSubmit
returns it to the dom. I seem to be missing something here and do not know what it is.

I'd like to do this where a when a user answers one question, they are asked 2 more questions before everything is posted to the DOM.

It's not posting nor working, I get no error to know what's going on, it simply won't write to the DOM

my code is:

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

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

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

handleSubmit(event) {
event.preventDefault();
console.log('submit worked!!!');
return <div>{this.state.value}</div>;
}

render() {
return (
<div
style={{
marginTop: '50px',
color: 'white',
top: '25px',
position: 'absolute'
}}
>

<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>

</div>
);
}
}

export default NameForm;


Thank you in advance

Answer Source

It seems to me that you are binding the wrong thing as this then.

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

These mean that your value of this will always be the parent Component and not the event.target.value that you are trying to set.

Just remove the lines, and it should work, as this should become the caller context (e.g. the input field), which would mean that your event.target.value should get and set what is entered properly.

Also, instead of returning on the handleSubmit, you should set what is conditionally rendered inside the render() method, and handle submit should set a state property, like hasSubmitted, which you can check in the render to conditionally render a form or something else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download