Home > Software engineering >  How to add condition in React JS dynamic table?
How to add condition in React JS dynamic table?

Time:12-24

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!

CodePudding user response:

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)

CodePudding user response:

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

  • Related