mercredi 28 octobre 2020

How to display data on top of others instead of simultaneously with React checkboxes?

I am new to React and trying to build a TODO app. What I'm trying to achieve is: 1) after each checkbox's click, I would like to show its associated data on top of what is already displayed rather than simultaneously (i.e checkbox 2 displaying its data instead of replacing another checkbox's data).

I guess it has something to do with the way I'm storing and filtering my items but I'm struggling to find the way out.

Also, and for it to be perfect, 2) I'd like to remove the behaviour that checking/unchecking my checkboxes is performing the same action (i.e when all checkboxes are clicked, unticking one will call again its associated function rather than doing nothing and keep its data displayed on the screen) and 3) allowing the fact that some checkboxes cannot be both ticked at the same time (the Clear and Show all checkboxes for example).

Thanks in advance

CODE

import React from "react";
import ReactDOM from "react-dom";
import Items from "./Items.js"

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    Data: Items,
    storeData: Items,
    }
  }

  myFunction = (category) => {
    const filterData = this.state.Data.filter(elem => elem.category === category);
    this.setState({storeData: filterData});
  }

  myFunctionAll = () => {
    this.setState({storeData: Items});
  }

  render() {
    console.log(this.state.storeData)
    console.log(this.state.Data)
    return(
      <div>
        <label>
          Filter A
          <input type="checkbox" onClick={() => this.myFunction("A")} />
        </label>
        <label>
          Filter B
          <input type="checkbox" onClick={() => this.myFunction("B")} />
        </label>
        <label>
          Filter C
          <input type="checkbox" onClick={() => this.myFunction("C")} />
        </label>
        <label>
          Clear All
          <input type="checkbox" onClick={() => this.myFunction(null)} />
        </label>
        <label>
          Show All
          <input type="checkbox" onClick={() => this.myFunctionAll()} />
        </label>

        <br />
        {this.state.storeData.map(elem => (
          <li key={elem.id}>
            Id: {elem.id} Category: {elem.category}
          </li>))}
      </div>
    )
  }
}

ReactDOM.render(<Checkbox />, document.getElementById("root"))

DATA

const Items = [
    {
      "id": 1,
      "name": "First item",
      "category": "A"
    },
    {
      "id": 2,
      "name": "Second item",
      "category": "B"
    },
    {
      "id": 3,
      "name": "Third item",
      "category": "C"
    },
    {
      "id": 4,
      "name": "Fourth item",
      "category": "A"
    },
  ]
  
  export default Items



Aucun commentaire:

Enregistrer un commentaire