51

I'm creating a simple CRUD app using React for my front-end, and I'm having trouble with this error:

app.js:21988 Warning: Invalid DOM property `for`. Did you mean `htmlFor`?

Here's my code:

import React, { Component } from 'react';
import axios from 'axios';

export default class Add extends Component {

    constructor()
    {
        super();
        this.state={
            blogs_name:''

        }
    }


    render() {
        return (
            <div>
                <form>
                     <div className="form-group">
                        <label for="blogs_name">Title</label>
                        <input
                            type="text"
                            className="form-control"
                            id="blogs_name" 
                            value={this.state.blogs_name} 
                        />
                    </div>
                    <button type="submit">Submit</button>
                </form>
            </div>
        );
    }
}

I assume that it has to do something with the for property in my label.

Any help is appreciated.

JCollier
  • 1,102
  • 2
  • 19
  • 31
Ledah Xille
  • 521
  • 1
  • 5
  • 4
  • Does this answer your question? [React ignores 'for' attribute of the label element](https://stackoverflow.com/questions/22752116/react-ignores-for-attribute-of-the-label-element) – Emile Bergeron Jan 27 '20 at 02:37

4 Answers4

99

When using React, you can't use the for keyword in JSX, since that's a javascript keyword (remember, JSX is javascript so words like for and class can't be used because they have some other special meaning!)

To circumvent this, React elements use htmlFor instead (see React docs for more information).

So, your render function should be (I only replaced for with htmlFor):

render() {
    return (
        <div>
            <form onSubmit={this.onSubmit} >
                <div className="form-group">
                    <label htmlFor="blogs_name">Title</label>
                    <input type="text" className="form-control" id="blogs_name" 
                        value={this.state.blogs_name} 
                    onChange={this.onChangeBlogsName} />
                </div>
                <button type="submit" className="btn btn-primary">Submit</button>
            </form>
        </div>
    );
}
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
20

Replace for="" with htmlFor=""

In your case change this

<label for="blogs_name">Title</label>

To this

<label htmlFor="blogs_name">Title</label>
Abdulhakim Zeinu
  • 3,333
  • 1
  • 30
  • 37
7

for is a reserved word in JavaScript this is why when it comes to HTML attributes in JSX you need to use something else, React team decided to use htmlFor respectively. You can check the list of attributes from here

Ronak Lalwani
  • 376
  • 2
  • 9
-5

Short answer, Remove

for="blogs_name"

In your case.

superup
  • 1,765
  • 13
  • 12