chichi
chichi

Reputation: 3302

How can I set my button or icon color to be different when a user is at the certain component?

I have drawer buttons here and I want to change Icon colors when a user clicks to each button and stays there. Like, if users click 'Dashboard' and are staying in that components, the dashboard button color will be white so that the buttons are indicating where users are in the website

 const drawer = (
    <div>
      <Button
        variant='contained'
        color='secondary'
        onClick={handleToDashboard}
        className={classes.customButton}
        startIcon={<DashboardIcon style={{ color: 'black' }} />}
      >
        Dashboard
      </Button>
      <Button
        variant='contained'
        color='secondary'
        onClick={handleToTest}
        className={classes.customButton}
        startIcon={<MapIcon />}
      >
       Map
      </Button>
      <Divider />
    </div>
  );

Upvotes: 1

Views: 171

Answers (1)

dev9
dev9

Reputation: 56

If this component is self-contained – that is, it doesn't load a new route whenever a user clicks a button, and instead remains on the existing page – you should maintain state (using setState if this is a class component or the useState hook for a functional component) that keeps track of whichever button was last pressed. You can update the state in your onClick callbacks and then make your color props conditional – for example:

<Button
    variant='contained'
    color={this.state.opened === 'map' ? 'white' : 'secondary'}
    onClick={handleToTest}
    className={classes.customButton}
    startIcon={<MapIcon />}
>

If this is part of a navigation bar that handles routing between pages, then you should pass as a prop from whatever component is being displayed the value in the drawer that should be highlighted. So for instance, the Dashboard component could, if it has this drawer as a child, pass a prop telling the drawer that it should render the dashboard button color white.

Upvotes: 1

Related Questions