React.js - Updating icon styles on component mount/unmount

129 Views Asked by At

I have an app that I'm building where it has a navigation bar down the left hand side with icons that open a modal when clicked on:

enter image description here

I have successfully set this up so that a different modal is loaded whenever the user clicks on one of the icons in the navigation bar and I'm now try to update state to highlight which icon's modal is loaded like the below:

enter image description here

To achieve this I am getting to grips with parent/child relationships and manipulating state.

The parent element renders a <div> that captures state:

<div>
   <ActiveDashboardIcon data={this.state.data} />
</div>

I then have a child function that populates the parent <div>:

const ActiveDashboardIcon = ({ data }) =>
    <div>
        {data ? data :
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'black' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'white' }} />
                </ListItemIcon>
            </ListItem>
        }
    </div>;

Lastly I am updating on componentDidMount and componentWillUnmount so that it updates the button styles (icon color and background color):

componentDidMount() {
    this.setState({
        data:
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'white' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'black' }} />
                </ListItemIcon>
            </ListItem>
    })
}

componentWillUnmount() {
    this.setState({
        data:
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'black' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'white' }} />
                </ListItemIcon>
            </ListItem>
    })
}

This works mostly as intended but I am struggling to accomplish a few things:

  1. This current approach works for one icon/modal combination but is difficult to scale as I am unable to define different componentDidMount functions for each icon/modal combination
  2. My current approach doesn't currently 'unselect' the icon and revert it to it's original style on componentWillUnmount
  3. I can't work out how to include an onClick property for the icon: onClick={this.openModal("dashboard")}. When I try to include it in the child element the browser cannot read property 'openModal' as it is part of the parent.

I am unsure of the best approach to achieve what I'm after.

0

There are 0 best solutions below