Home > Net >  Change Bootstrap class depending of component state in React
Change Bootstrap class depending of component state in React

Time:06-20

I have a react component called NavBar. It gets a variable from another component (App.js) which specifies if the page is in dark mode or not. The variable is called "pageMode". I want to change the class of the navBar from navbar-light to navbar-dark depending of the value of the "pageMode" var.

Here´s the code

import React from 'react';

class NavBar extends React.Component{ 

render(){

if(this.props.pageMode === "dark"){
    //Here I want to do something to render the component using navbar-dark class
}
else{
    //Render using navbar-light class
}

return <nav className="navbar navbar-expand-lg [navbar-light] bg-light">
    <a className="navbar-brand NavBar-title-fix" href="#">Inicio</a>
    <button className="navbar-toggler" type="button" data-toggle="collapse" data- 
     target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- 
    expanded="false" aria-label="Toggle navigation">
        <span className="navbar-toggler-icon"></span>
    </button>
    
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
        <ul className="navbar-nav mr-auto">
        <li className="nav-item active">
            <a className="nav-link" href="#">Proyectos</a>
        </li>
        <li className="nav-item">
            <a className="nav-link" href="#">Sobre mi</a>
        </li>
        </ul>
    </div>
</nav>  
}  
}

export default NavBar;

In the render return state the class between [] is the one that i want to be changed depending of the variable value.

Thanks for reading!

CodePudding user response:

import React from 'react';

class NavBar extends React.Component{ 

render(){

const themeClass = {
  dark: '[navbar-dark]',
  light: '[navbar-light]'
}[this.props.pageMode]

return <nav className={`navbar navbar-expand-lg ${themeClass} bg-light`}>
    <a className="navbar-brand NavBar-title-fix" href="#">Inicio</a>
    <button className="navbar-toggler" type="button" data-toggle="collapse" data- 
     target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- 
    expanded="false" aria-label="Toggle navigation">
        <span className="navbar-toggler-icon"></span>
    </button>
    
    <div className="collapse navbar-collapse" id="navbarSupportedContent">
        <ul className="navbar-nav mr-auto">
        <li className="nav-item active">
            <a className="nav-link" href="#">Proyectos</a>
        </li>
        <li className="nav-item">
            <a className="nav-link" href="#">Sobre mi</a>
        </li>
        </ul>
    </div>
</nav>  
}  
}
  • Related