Search code examples
reactjsjsxreact-tablereact-table-v7

Trying to compare the value of two cells in react, then change style based on value


I am new to react.

I made a table using react-table module I'm trying to highlight all the cells where the cell in the first column doesn't equal the cell next to it in column 2.

here is my table component:

const Table = () => {

    const columns = useMemo(() => Columns, [])
    const data = useMemo(() => mock, [])
    
    

    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
        state,
        setGlobalFilter,
    } = useTable({
        columns,
        data,
    }, useGlobalFilter)

    const { globalFilter } = state

    return (
        < >
         
            <SearchBar searchValue={globalFilter} setSearchValue={setGlobalFilter}/>
            
           
        <div>
            
            <table {...getTableProps()}>
                <thead>

                    
                    {headerGroups.map((headerGroup) =>(
                        <tr {...headerGroup.getHeaderGroupProps()}>
                            {headerGroup.headers.map((column) => (
                                <th {...column.getHeaderProps()}>
                                    {column.render('Header')}
                                </th>
                            ))}
                        </tr>
                    ))}
                        
                </thead>
                <tbody {...getTableBodyProps()}>
                    {
                        rows.map((row) =>{
                            prepareRow(row)
                            return (
                                <tr {...row.getRowProps()}>
                                    {row.cells.map((cell, index)=> {
                                        return <td {...cell.getCellProps()} style = {{
                                            backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null}
                                        }}>{cell.render('Cell')}</td>
                                    })} 
                                </tr>
                            )
                        })
                    }
                    
                </tbody>
            </table>
        </div>
        </>
    )


        

    
}


export default Table

when I run this I get two errors

expected ',' at

backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null}

expected ':' at

backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null}

any help would be really appreciated


Solution

  • {backgroundColor:(rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null)}
    

    use parentheses not braces.