vendredi 5 avril 2019

React / How to pass the condition when checkbox is checked

I'm making ToDo List app in React.

In Form component, I put a checkbox. If checkbox is checked, I want to display the word "Important" on Item component. In order to accomplish this I know I should update state, but now I'm confused how to pass "checked" condition from where to where.

I set state on App component, but I can't update the state from Form component. Also, I don't know how Item component can recognize if checkbox is checked.

class App extends React.Component {

   state = { defaultList: todo, checked: false }

    onSubmit = (task) => {        
        this.state.defaultList.push({task});
        this.setState(todo);
    }

    handleCheckBox = () => {

    }

    render() {
        return (
            <div>
                <Form 
                    onSubmit = {this.onSubmit}
                    checkCheckBox = {this.handleCheckBox}
                />
                <List 
                    lists = {this.state.defaultList}
                />
            </div>
        );
    }
}

class Form extends React.Component {

    onFormSubmit = (event) => {
        event.preventDefault();

        this.props.onSubmit(this.refs.userInput.value);
        this.refs.userInput.value = "";
    }

    handleCheckClick = () => {
        this.props.setState({ checked: !this.props.state.checked });
    }

    render() {
        return (
            <div>
                <form onSubmit={this.onFormSubmit}>
                    <div>
                        <label>Task</label>
                        <input ref="userInput" />
                        <p className="warning"></p>
                    </div>
                    <div>
                        <input 
                        type="checkbox" 
                        checkCheckBox={this.handleCheckClick} 
                        onChange={this.handleCheckClick} 
                        />
                        <label>Important</label>
                    </div>
                        <button type="submit">ADD</button>
                </form>
            </div>
        );
    }
}

const List = ({lists}) => {
    const renderedList = lists.map((list) => {
        return (
            <Item 
                task = {list.task}
                priority = {list.priority}
            />
        );
    });

    return <div>{renderedList}</div>
}


const Item = ({task, priority, checkChecked}) => {
    return (
        <ul>
            <li><b>{task}</b></li>
            <li>
            {checkChecked && <span>{priority}</span>} // Write a if statement here
            </li>
            <li>Delete</li>
        </ul>
    );
}




Aucun commentaire:

Enregistrer un commentaire