HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactModerate

How to get the value of an input field using ReactJS?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
getfieldthevaluereactjsinputusinghow

Problem

I have the following React component:

export default class MyComponent extends React.Component {

    onSubmit(e) {
        e.preventDefault();
        var title = this.title;
        console.log(title);
    }

    render(){
        return (
            ...
            
                ...
                 this.title = c} name="title" />
                ...
            
            ...
            Save
            ...
        );
    }

};


The console is giving me undefined - any ideas what's wrong with this code?

Solution

You should use constructor under the class MyComponent extends React.Component

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }


Then you will get the result of title

Code Snippets

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

Context

Stack Overflow Q#36683770, score: 24

Revisions (0)

No revisions yet.