Beda
Beda

Reputation: 107

Change background-color of component depending on where i call it

I've got a problem I can't seem to solve.

I use a component several times in my app but I'd like the background to be different.

I've declared an empty state for the moment, which I'm using in background-color but I can't define the color the component will have. How can I do this?

Thanks for your help

Here is a little piece of my code :

class Gallery extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      activeGal: [],
      width: 1920,
      teamGal: {},
      isOpen: false,
      photoIndex: 0,
      bgColor: ''
    }
}

render() {
    const {activeGal, width, teamGal, isOpen, photoIndex, bgColor} = this.state

.gallery {
            background-color: ${bgColor};
            padding-bottom: 55px;
          }

Upvotes: 0

Views: 278

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

The easiest (and not recommended) way is to use the style prop:

class Gallery extends React.Component {
  render() {
    const { backgroundColor } = this.props;
    return <div style={{ width: "100%", height: "100%", backgroundColor }} />;
  }
}

const App = () => {
  return (
    <div style={{ height: "50vh", width: "50vw" }}>
      <Gallery backgroundColor="blue" />
    </div>
  );
};

Edit nifty-hopper-n719w

More popular solutions are using CSS-in-JS (like styled-components) or CSS variables (See CSS Variables for React Devs).

Upvotes: 2

Related Questions