Home > Back-end >  How do you style your React.js components differently depending on where you are using them in your
How do you style your React.js components differently depending on where you are using them in your

Time:08-09

Let's say you have a navbar and when you're using this component on your homepage you want it to have a certain background color and display property, but when you use that same navbar component on another page in your application you want to change these CSS properties. Seeing as the component has one CSS file linked how would you change the style of a component depending on where it is being rendered?

CodePudding user response:

My personal favourite method nowadays is styled components. Your component might look something like this:

// NavBar.js
import styled from 'styled-components'

const StyledDiv = styled.div`
  width: 100%;
  height: 2rem;
  background-color: ${props => props.bgColor};
`

const NavBar = (bgColor) => {
    return <StyledDiv bgColor={bgColor}>
}

Then to use it in your different contexts you simply pass the color prop:

// homepage.js
<NavBar bgColor="red" />

// otherpage.js
<NavBar bgColor="#123ABC" />

Styled components are becoming a very popular way of doing things, but be aware that there are a huge array of ways you can do this.

https://styled-components.com/

(Code not tested)

CodePudding user response:

Well If you just want to use plain CSS then you can change the className based on route so the styles also changes.

Example:

import { useLocation } from "react-router-dom";

const Navigation = () => {
    let location = useLocation();
   ...
   return(
       <nav className={location.pathname === "/home" ? "homepage-navbar" : "default-navbar"}>
            ...
       </nav>
   )
}

You can write longer condition for multiple pages as well.

Other better thing you can do is pass the location.pathname and value of className as prop.

import { useLocation } from "react-router-dom";

const Home = () => {
    let location = useLocation();
    ...
    return (
        <>...
           <Navigation location={location.pathname} styleClass={"homepage-navbar"}/>
        </>
    )
}
const Navigation = ({location, styleClass}) => {
   ...
   return(
       <nav className={location === "/home" ? styleClass : "default-navbar"}>
            ...
       </nav>
   )
}

So now you can pass different values for className from different components and get different styles for the navbar.

  • Related