Search code examples
reactjsfirebasereact-hooksmaterial-uiredux-observable

Dynamically updating background color when user signs in but when he sign out,the background color does not changes but only on reload


This is the code snippet for what I am trying to do. currentUser is updated when the user signs in or logs out.

interface StyleAppBar {
    backgroundColor: string;
    boxShadow: string;
}

const useStyles = makeStyles<Theme, StyleAppBar>((theme) =>
    createStyles({
        appBar: {
            background: (muiProps) => muiProps.backgroundColor,
            boxShadow: (muiProps) => muiProps.boxShadow,
        },
    })
);

const Navbar: FC<NavbarProps> = (props) => {
    const { currentUser, signOut } = props;


    const muiProps = {
        backgroundColor: currentUser ? 'white' : 'primary',
        boxShadow: currentUser ? 'none' : 'primary',
    };

    const classes = useStyles(muiProps);

    return (
        <div>
            <AppBar position="static" className={classes.appBar}>

The other implementation I tried worked as when the user signed out, the color is changing back as specified in the code. In the implementation, I defined useStyles inside Navbar component not outside as seen in above component. Though I feel this might not be the correct approach. Please let me know if there is other efficient work around. I am using Material-UI, React , Redux-Observable , Firebase. Thank you


Solution

  • Perhaps this option will solve your problem:

    const useStyles = makeStyles(theme => ({
      appBar1: {
        background: 'white',
        boxShadow: 'none',
      },
      appBar2: {
        background: 'primary',
        boxShadow: 'primary',
        },    
    }));
        
    const Navbar: FC<NavbarProps> = (props) => {
        const { currentUser, signOut } = props;
        const classes = useStyles();
    
        return (
            <div>
                <AppBar position="static" className={currentUser ? classes.appBar1 : classes.appBar2}>   
        ...