1

I was trying this code in react, but I was getting this error:

Unexpected Token .

I was trying to bind the value to something on html, and see if change in value reflects on the html, like a angular ng-bindings.

Code:

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('A name was submitted: ' + this.state.value);
        event.preventDefault();
    }

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

ReactDOM.render(
    <NameForm />,
    document.getElementById('root')
);

Can someone tell me where I am going wrong.

1 Answer 1

4

Reason is, you are returning more than one html element from render method, In a component's render, you can only return one node; if you have, say, a list of elements to return, you must wrap those within a div, span or any other component.

Don't forget that the render() is basically a function, Functions always take in a number of parameters and always return exactly one value.

Use this:

return (
   <div>
       <form onSubmit={this.handleSubmit}>
         <label>
           Name:
           <input type="text" value={this.state.value} onChange={this.handleChange} />
         </label>
         <input type="submit" value="Submit" />
       </form>
       <a>{this.state.value}</a>
   </div>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.