简体   繁体   中英

How to add condition in React JS dynamic table?

I have a react js dynamic table as given below: now I want to add condition in this dynamic table. but condition only working with values all the header still displaying.

I need to display email and mobile fields conditional.

My Code:

 const App = (props) => { const [condition, setCondition] = useState(true); var colums = [{ Header: "Name", accessor: "name", }, { width: 150, Header: "Email", accessor: "email", Cell: (props) => { return ( < > { condition? < div > { props.row.values.email } < /div>: ""}</ > ); }, }, { width: 150, Header: "Phone", accessor: "phone", Cell: (props) => { return ( < > { condition? < div > { props.row.values.phone } < /div>: ""}</ > ); }, }, ] return ( <> <BasicTable columns ={colums} tableType = "default"> </BasicTable> export default App;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Thanks for your efforts!

You would have to set your condition at the array level, something like this should work:

Edit: Avoid having empty objects.

var colums = [
    {
      Header: "Name",
      accessor: "name",
    },
     (condition && {
      width: 150,
      Header: "Email",
      accessor: "email",
      Cell: (props) => {
        return (
          <>{<div>{props.row.values.email}</div>}</>
        );
      },
    }),
    (condition && {
    width: 150,
    Header: "Phone",
    accessor: "phone",
    Cell: (props) => {
      return (
        <>{<div>{props.row.values.phone}</div>}</>
      );
    }})
].filter(item => item)

keep columns array 'full' and then just filter items depending on condition. In separate function or just in callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM