Home > Software engineering >  How to change Button Color and Name in specific cell in Material UI Table
How to change Button Color and Name in specific cell in Material UI Table

Time:10-17

I am using Material Table for Showing my Data. Here it looks like, https://i.postimg.cc/4x6hbm5N/image.png

I have declared a state above in my code

const [sharedOrdersList, setShareOrdersList] = useState([])

When the User click the Share button, I will push the Order Id to sharedOrdersList. It works. But now my issue was i want to change the Button Name to UnShare and button color to another color. I tried several ways. But I don't know how to make it

Here's my Function Code:

 const shareOrderBtnClick = (orderID) => {
    sharedOrdersList.push(orderID)

    alert("share Btn Clicked")
    console.log(sharedOrdersList)
  }

Return Code:

allOrderDatas.map((row) => (
        <TableRow>
         <TableCell">
                <Button variant="contained" 
                  onClick={()=>{shareOrderBtnClick(row.orderID)}}
                   style={{ backgroundColor:sharedOrdersList.includes(row.orderID)?"#59886B":"#D54062",}}> 
    <ShareIcon />{sharedOrdersList.includes(row.orderID)?"UnShare":"Share"</Button>
          </TableCell>
         </TableRow>

I don't know how to change the specific item in the cell in the row in table. Please Help me with some solutions.

CodePudding user response:

states in react are immutable. useState returns a value and an updater function. You can't directly change the value. To update the state you need to call setShareOrdersList function with the new value.

In you're example

const shareOrderBtnClick = (orderID) => {
    setShareOrdersList([... sharedOrdersList, orderID]); 
// OR BETTER
//   setShareOrdersList(prevState => [...prevState, orderID]);
  }
  • Related