0

I am learning reactjs and javascript. I have written a reactjs crud app. it is working fine.

Now i want to implement my form should be show on click button ADD NEW

My component name is <Form>

Here you go for my home.js file

import React from "react"
import Table from "./table"
import Form from "./form"

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            current: 'SAVE', // button name
            employees: [{name: 'jhon', age: '23', email: 'a@a'}, {name: 'doe', age: '24', email: 'b@a'}],
            currentEmp: {},
        };
        this.onSubmit = this.onSubmit.bind(this);
        this.onDelete = this.onDelete.bind(this);
        this.setIndex = this.setIndex.bind(this);
    }

    onSubmit(name, age, email, index=null) {
        if(!index && this.state.current == 'SAVE'){
            this.setState({ employees: [...this.state.employees, { name: name, age: age, email: email }] });
        }
        else if(this.state.current == 'Update'){
            var emp = this.state.employees;
            emp[this.state.index].name = name;  //use index from state
            emp[this.state.index].age = age;
            emp[this.state.index].email = email;
            this.setState({
                currentEmp: {},
                employees: emp,
                current: 'SAVE'
            });
        }
        else{
            this.setState({
                currentEmp: {},
                current: 'SAVE',
            });
        }
    };

    setIndex(index){
        var emp = this.state.employees[index];
        emp.index = index;
        this.setState({
            currentEmp: emp,
            current: 'Update',
            index  //set index in state
        });
    }


    // delete employee
    onDelete(event, index) {
        this.setState({
            employees: this.state.employees.filter((item, itemIndex) => (index != itemIndex)),
        });
    };

    render() {
        return (
            <React.Fragment>
              <h1>Employee Information System</h1>

              <div>
              <Form
                currentEmp={this.state.currentEmp}
                submitMe={this.onSubmit}
                currentButtonName={this.state.current} />
              </div>

              <button>ADD NEW</button>

            <hr/>
            <table className="table table-striped table-dark">
                <Table onUpdateTry={this.edit} editThis={this.setIndex} employees={this.state.employees} deleteMe={this.onDelete} />
            </table>
            <p className="test">Ignore this please ! Just showed if sass works or not</p>

            </React.Fragment>
        );
    }
}
export default Home;

above script, you will see a button named ADD NEW and above it, you will see a component name Form inside a div

I Want when i click on the button, then the DIV should be shown.

Can anyone please help me to achieve this?

3 Answers 3

1
  1. You'll need to add formVisible: false to your state.

  2. You will need to define this method:

handleFormVisibility = () => {
  this.setState({ formVisible: true });
}

PS: You will not be needing to bind(this) this method because it's declared using ES6 Arrow Function syntax.

  1. Refactor:
  {
    this.state.formVisible ? (
      <Form
        currentEmp={this.state.currentEmp}
        submitMe={this.onSubmit}
        currentButtonName={this.state.current} />
    ) : null
  }
  <button onClick={this.handleFormVisibility}>ADD NEW</button>

PS: this.state.formVisible ? 'ReturnIfTrue' : 'ReturnIfFalse' this is a ternary operation, introduced in ES6, which will examin this.state.formVisible, if it's true we place what we want to return at the first statement ReturnIfTrue and the opposite at ReturnIfFalse.

If there is something that not clear please go ahead and ask.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you made my day
@dudd I appreciate it!
1

This can also help:

import React from "react" import Table from "./table" import Form from "./form"

class Home extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        current: 'SAVE', // button name
        employees: [{name: 'jhon', age: '23', email: 'a@a'}, {name: 'doe', age: '24', email: 'b@a'}],
        currentEmp: {},
        show:false
    };
    this.onSubmit = this.onSubmit.bind(this);
    this.onDelete = this.onDelete.bind(this);
    this.setIndex = this.setIndex.bind(this);
    this.handleShow=this.handleShow.bind(this)
}
handleShow(){
    this.setState({show:!this.state.show})
}
onSubmit(name, age, email, index=null) {
    if(!index && this.state.current == 'SAVE'){
        this.setState({ employees: [...this.state.employees, { name: name, age: age, email: email }] });
    }
    else if(this.state.current == 'Update'){
        var emp = this.state.employees;
        emp[this.state.index].name = name;  //use index from state
        emp[this.state.index].age = age;
        emp[this.state.index].email = email;
        this.setState({
            currentEmp: {},
            employees: emp,
            current: 'SAVE'
        });
    }
    else{
        this.setState({
            currentEmp: {},
            current: 'SAVE',
        });
    }
};

setIndex(index){
    var emp = this.state.employees[index];
    emp.index = index;
    this.setState({
        currentEmp: emp,
        current: 'Update',
        index  //set index in state
    });
}


// delete employee
onDelete(event, index) {
    this.setState({
        employees: this.state.employees.filter((item, itemIndex) => (index != itemIndex)),
    });
};

render() {
    return (
        <React.Fragment>
          <h1>Employee Information System</h1>
          {this.state.show?
           <div>
          <Form
            currentEmp={this.state.currentEmp}
            submitMe={this.onSubmit}
            currentButtonName={this.state.current} />
          </div>
          :null                   
          }


          <button onClick={()=>this.handleShow()}>ADD NEW</button>

        <hr/>
        <table className="table table-striped table-dark">
            <Table onUpdateTry={this.edit} editThis={this.setIndex} employees={this.state.employees} deleteMe={this.onDelete} />
        </table>
        <p className="test">Ignore this please ! Just showed if sass works or not</p>

        </React.Fragment>
    );
}

} export default Home;

1 Comment

I wouldn't render the thing then css hide it, we shouldn't render things if we don't want to show them for the sake of Performance and better UI Development experience.
1

You can make use of state to conditionally render elements.

isFormVisible = false  //add this line to your existing state

And the condition,

{this.state.isFormVisible && <div>
     <Form
        currentEmp={this.state.currentEmp}
        submitMe={this.onSubmit}
        currentButtonName={this.state.current} />
     </div>
}

And your button should be,

<button onClick={() => this.setState({isFormVisible:true})}>ADD NEW</button>

2 Comments

Should have used ternary operator, instead of && because it returns false if the condition wasn't valid, false is not considered as a Valid React Element.
If the isFormVisible is false, then entire div will not get added to DOM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.