简体   繁体   中英

How do I render component based on state

I've got this filter Icon from MaterialUI and I need it to be filled black (for now it can change position) when a checkmark is checked. When a box is checked setFilters is filled. So if a check is Product Type is ticked, setFilters(prt:[]) wont be empty.

How do I make it so that if setFilters(prt:[]) is not empty, I can render the filter icon with a different position (eventually i'll render a different icon).

I've already tried

 { props.filters > 0 && d.autoFilter? <FiFilter style={{position:"relative", top:"4px", left: "12px"}} onClick={() => props.toggleVisibleFilter(d.field)}/>:<div/>}

 // component A const [filters, setFilters] = useState({search:'',prt:[],cnt:[],cat:[]}) // Component B const headerFields = [ {field: 'ID', label: '', width: '5%'}, {field: 'bnd', label: 'Brand', width: '15%' }, {field: 'cnt', label: 'Country', autoFilter: true, width: '15%' }, {field: 'prt', label: 'Product type', autoFilter: true, width: '20%' }, {field: 'cat', label: 'Category', autoFilter: true, width: '20%' }, {field: 'url', label: 'URL', width: '25%' }, ] // JSX <TableRow> {headerFields.map((d)=> <TableCell classes={{ root:classes.root }} style={{ textAlign:"left",fontSize:"18px", position:"sticky", width:d.width, background:"#F28808"}} align="left">{d.label} { d.autoFilter? <FiFilter style={{position:"relative", top:"4px", left: "4px"}} onClick={() => props.toggleVisibleFilter(d.field)}/>:<div/>} {props.visibleFilter===d.field?<MultiSelectFIlter filterHandler={props.filterHandler} API_DATA={props.API_DATA} visibleFilter={props.visibleFilter} setVisibleFilter={props.setVisibleFilter} setFilters={props.setFilters} filters={props.filters} />:(null)} </TableCell> )} </TableRow>

在此处输入图像描述

You can use conditional approach like this

style={`${filters==[]} ? {display:"none"} : {display:"block"} `}

From your conditional above, you have an error. For when you check if the array is empty or not you must check the length of it not just props.filters but instead props.filters.length in order for the conditional to work, otherwise while array is defined and the length is 0 the props.filters will always return true;

also since in your case you have defined it like:

 const [filters, setFilters] = useState({search:'',prt:[],cnt:[],cat:[]})

your conditional should be something like this:

{ props.filters.prt.length > 0 ? ...

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