javascript - Using react, how would I hide a table row on click? - Stack Overflow

Hey guys I am using this table to display data and I added a button to each row. How would I be able to

Hey guys I am using this table to display data and I added a button to each row. How would I be able to hide a row when I click the hide button next to it?

I am aware of a way to do within html elements but not sure how to hide a particular row within a table thats within a loop

Can anyone show me how to acplish this?

Thank you

import React, { Component } from 'react'

class Table extends Component {
   constructor(props) {
      super(props) //since we are extending class Table so we have to use super in order to override Component class constructor
      this.state = { //state is by default an object
         students: [
            { id: 1, name: 'Wasif', age: 21, email: '[email protected]' },
            { id: 2, name: 'Ali', age: 19, email: '[email protected]' },
            { id: 3, name: 'Saad', age: 16, email: '[email protected]' },
            { id: 4, name: 'Asad', age: 25, email: '[email protected]' }
         ]
      }
   }

   renderTableData() {
    return this.state.students.map((student, index) => {
       const { id, name, age, email } = student //destructuring
       return (
          <tr key={id}>
             <td>{id}</td>
             <td>{name}</td>
             <td>{age}</td>
             <td>{email}</td>
             <td><button>HIDE</button></td>
          </tr>
       )
    })



 }
renderTableHeader() {
      let header = Object.keys(this.state.students[0])
      return header.map((key, index) => {
         return <th key={index}>{key.toUpperCase()}</th>
      })
   }







   render() { //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
    return (
      <div>
         <h1 id='title'>React Dynamic Table</h1>
         <table id='students'>
            <tbody>
               <tr>{this.renderTableHeader()}</tr>
               {this.renderTableData()}
            </tbody>
         </table>
      </div>
   )
}
}

export default Table 

Hey guys I am using this table to display data and I added a button to each row. How would I be able to hide a row when I click the hide button next to it?

I am aware of a way to do within html elements but not sure how to hide a particular row within a table thats within a loop

Can anyone show me how to acplish this?

Thank you

import React, { Component } from 'react'

class Table extends Component {
   constructor(props) {
      super(props) //since we are extending class Table so we have to use super in order to override Component class constructor
      this.state = { //state is by default an object
         students: [
            { id: 1, name: 'Wasif', age: 21, email: '[email protected]' },
            { id: 2, name: 'Ali', age: 19, email: '[email protected]' },
            { id: 3, name: 'Saad', age: 16, email: '[email protected]' },
            { id: 4, name: 'Asad', age: 25, email: '[email protected]' }
         ]
      }
   }

   renderTableData() {
    return this.state.students.map((student, index) => {
       const { id, name, age, email } = student //destructuring
       return (
          <tr key={id}>
             <td>{id}</td>
             <td>{name}</td>
             <td>{age}</td>
             <td>{email}</td>
             <td><button>HIDE</button></td>
          </tr>
       )
    })



 }
renderTableHeader() {
      let header = Object.keys(this.state.students[0])
      return header.map((key, index) => {
         return <th key={index}>{key.toUpperCase()}</th>
      })
   }







   render() { //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
    return (
      <div>
         <h1 id='title'>React Dynamic Table</h1>
         <table id='students'>
            <tbody>
               <tr>{this.renderTableHeader()}</tr>
               {this.renderTableData()}
            </tbody>
         </table>
      </div>
   )
}
}

export default Table 
Share Improve this question asked Aug 26, 2020 at 13:15 JTHDRJTHDR 511 gold badge1 silver badge7 bronze badges 1
  • I used className attribute with with a class having display: 'none', we can also use inline style attribute on tr ( HTML ) / TableRow ( MUI ). – Manohar Reddy Poreddy Commented Jan 11, 2023 at 13:17
Add a ment  | 

4 Answers 4

Reset to default 1

You could add an onClick handler to the button that adds a property that determines the student should be hidden or not.

Notice the onClick={() => this.hideRow(id)} below.

renderTableData() {
  return this.state.students.map((student, index) => {
    const { id, name, age, email, isHidden } = student; //destructuring

    // isHidden will default to undefined if not found on the student object
    
    // user is hidden
    if (isHidden === true) {
      return null;
    }

    return (
      <tr key={id}>
        <td>{id}</td>
        <td>{name}</td>
        <td>{age}</td>
        <td>{email}</td>
        <td>
          <button onClick={() => this.hideRow(id)}>HIDE</button>
        </td>
      </tr>
    );
  });
}

The hideRow method will accept a student id and will add an isHidden: true attribute to the student with that id.

hideRow(id) {
  const students = this.state.students.map((student) => {
    // not same id? leave as is
    if (student.id !== id) {
      return student;
    }

    return { ...student, isHidden: true };
  });

  this.setState({ students });
}

Now you don't want to display the isHidden column, so you have to update renderTableHeader method to skip that.

renderTableHeader() {
  let header = Object.keys(this.state.students[0]);
  return header.map((key, index) => {
   
    // notice this
    if (key === "isHidden") {
      return null;
    }

    return <th key={index}>{key.toUpperCase()}</th>;
  });
}

Add a isVisible key in all objects like

 students: [
            { id: 1, name: 'Wasif', age: 21, email: '[email protected]', isVisible: true },
            { id: 2, name: 'Ali', age: 19, email: '[email protected]', isVisible: true },
            { id: 3, name: 'Saad', age: 16, email: '[email protected]', isVisible: true },
            { id: 4, name: 'Asad', age: 25, email: '[email protected]', isVisible: true }
         ]

Then in your render row function do this

renderTableData() {
    return this.state.students.map((student, index) => {
       const { id, name, age, email, isVisible } = student
       return isVisible ? (
          <tr key={id}>
             <td>{id}</td>
             <td>{name}</td>
             <td>{age}</td>
             <td>{email}</td>
             <td><button>HIDE</button></td>
          </tr>
       ) : null
    })

On button/row click update state.

Try this code

import React, { Component } from "react";

class Table extends Component {
  constructor(props) {
    super(props); //since we are extending class Table so we have to use super in order to override Component class constructor
    this.state = {
      //state is by default an object
      students: [
        { id: 1, name: "Wasif", age: 21, email: "[email protected]", toggle: true},
        { id: 2, name: "Ali", age: 19, email: "[email protected]", toggle: true },
        { id: 3, name: "Saad", age: 16, email: "[email protected]", toggle: true},
        { id: 4, name: "Asad", age: 25, email: "[email protected]", toggle: true }
      ]
    };
  }
  handleClick(index) {
    let students = [...this.state.students];
    students[index].toggle = !students[index].toggle;
    this.setState({ students });
  }
  renderTableData() {
    return this.state.students.map((student, index) => {
      const { id, name, age, email, toggle } = student; //destructuring
      if (toggle) {
        return (
          <tr key={id}>
            <td>{id}</td>
            <td>{name}</td>
            <td>{age}</td>
            <td>{email}</td>
            <`td`>
              <button
                value={index}
                onClick={(e) => this.handleClick(e.target.value)}
              >
                Hide
              </button>
            </td>
          </tr>
        );
      } else {
        return null;
      }
    });
  }
  renderTableHeader() {
    let header = Object.keys(this.state.students[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  }

  render() {
    //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
    return (
      <div>
        <h1 id="title">React Dynamic Table</h1>
        <table id="students">
          <tbody>
            <tr>{this.renderTableHeader()}</tr>
            {this.renderTableData()}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;

Follow these steps:

  1. Put an onclick on the button
  2. Pass the array as props to the ponent
  3. On the next ponent display the array
  4. Add the onclick method to it which is also passed as a props from the main ponent(Pass id as a parameter)
  5. In the method use a filter array to remove the row of your choice when you click it. The code is as follow:

https://codesandbox.io/s/modern-tdd-mlmzl?file=/src/ponents/Table.js

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744318089a4568280.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信