Sunday, October 14, 2018

ReactJS - How to remove whole component by using child button


Mr. Klisiu wants to create TODO app in ReactJS with functionality like:
  1. onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion )
  2. In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox"
Klisiu thinks his library may be wrong.

His code:
import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(
      <div>
        <div
          onClick={this.toggleHidden.bind(this)}
          className="addtask__btn">
          +
        </div>
        {this.state.isHidden && <AddTaskBox />}
      </div>
    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(
      <div className="addtask__box" >
        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>
      </div>
    );
  }
}

export {AddButton, AddTaskBox};

StackOverflow user, Donovan Hiland, answer:

Assuming by AddTaskComponent you mean AddTaskBox you would pass the toggleHidden function to AddTaskBox

{this.state.isHidden && <AddTaskBox onClose={this.toggleHidden.bind(this)} />}

and then call the function from the child on click

<button onClick={this.props.onClose}> x </button>



https://stackoverflow.com/users/7165303/donovan-hiland

No comments:

Post a Comment