Source:  Twitter logo

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.

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>
    );
}
71 users liked answer #0dislike answer #071
Ismael Padilla profile pic
Ismael Padilla

Replace for="" with htmlFor=""

In your case change this

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

To this

<label htmlFor="blogs_name">Title</label>
13 users liked answer #1dislike answer #113
Abdulhakim Zeinu profile pic
Abdulhakim Zeinu

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

6 users liked answer #2dislike answer #26
Ronak Lalwani profile pic
Ronak Lalwani

Short answer, Remove

for="blogs_name"

In your case.

-4 users liked answer #3dislike answer #3-4
superup profile pic
superup

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).