React component error on checked property [Solved]

React component error on checked property [Solved]
0

#1

I need some help with a pair of eyes… again…
I have a Todo app built with React, and within it I have the following structure:
TodoApp - main component
TodoList - a list with… Todo components…

The Todo components are very basic, they just take a text and show it to the user.
Near that text I wanted to add a checkbox, to show the user if the todo is completed or no.
I am sending the data from the TodoApp > TodoList > Todo…

The problem
When on the Todo component, I add for the checkbox the checked property, the app brakes… and I just don’t understand why…

The Todo component where I get the error:

var Todo = React.createClass({
    render: function() {
        var {text, completed} = this.props;

        return (
            <div>
                <input type="checkbox" checked={completed}/>
                {text}
            </div>
        );
    }
});

The github repo can be found here.
I bet is something so easy to fix, and I just can’t see it. :slight_smile:


#2

I’ll try to help you out, a suggestion

getInitialState: function(){
  return {
    show: false,
    search: "",
    todos: []
  }  
},

You usually don’t pass along all the data when you initialize the state, instead, you use componentWillMount or componentDidMount and then use setState to give your state initial values.

I’ll try to look into your app, however your repository isn’t updated, please commit your changes.


#3

I didn’t try, but I think the problem is because you try to edit a props ( passing it directly in checked ).

Try adding getInitialState:

getInitialState () {
  return { completed: this.props.completed };
}

and in render:

...
  return (
    <div>
      <input type="checkbox" checked={this.state.completed} onChange={() => this.setState ({ completed: !this.state.completed })} />
      {this.props.text}
    </div>
  );

#4

Sorry about that… I updated the github repo.


#5

Maybe it’s because checked doesn’t accept attributes?


#6

The instructor from the course is doing the exact same thing… :thinking:


#7

I don’t change the property, I just get the value with this.props, so I can show it checked or unchecked depending on the completed boolean value.

Also, the Todo component doesn’t hold the state… So the code you gave me won’t be functional.


#8

Yes, I’ve cloned your repo, start the server and when I try to check I get this warning:

warning.js?8a56:36 Warning: Failed form propType: You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly. Check the render method of Todo.


#9

Thank you… That solved the issue…
Seems that the instructor is using another react version.

I had to use defaultChecked property instead of checked.

What tool you used to get that warning?