Exploring the concept of utilizing CSS modules within React: What is the proper technique for passing a className as a prop to

When working with CSS Modules in a React component, how can I pass a className that includes the hash generated css module name? Currently, it only provides the className itself, like this:

<div className={styles.tile + ' ' + styles.blue}>

Below is the code for my custom Tile.js component:

import React, { Component } from 'react';

import styles from './Tile.css';

class Tile extends Component {

  render() {

    return (
      <div className={styles.tile + ' ' + this.props.color}>
        {this.props.children}
      </div>
    );
  }
};

export default Tile;

The corresponding CSS file, Tile.css, looks like this:

@value colors: "../../styles/colors.css";
@value blue, black, red from colors;

.tile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
}

.black {
  background-color: black;
}

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

To use the Tile component and pass a color prop, you would include it in another component, such as AuthorTile.js:

return (
  <Tile orientation='blue'>
   <p>{this.props.title}</p>
   <img src={this.props.image} />
  </Tile>
);

Answer №1

According to the documentation:

It is recommended to avoid using multiple CSS Modules for defining a single element. https://github.com/gajus/react-css-modules#multiple-css-modules

@value colors: "../../styles/colors.css";
@value blue, black, red from colors;

.tile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
}

.black {
    composes: tile;
    background-color: black;
}

.blue {
    composes: tile;
    background-color: blue;
}

.red {
    composes: tile;
    background-color: red;
}

Using

<div className={styles[this.props.color]}
should suffice, for example:

render: function(){
  // ES2015
  const className = styles[this.props.color];

  // ES5
  var className = '';

  if (this.props.color === 'black') {
    className = styles.black;
  }

  return (
    <div className={className}>
      {this.props.children}
    </div>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Easily changing the state of a specific array item using React

I'm having trouble updating the state of a specific item in an array called reviews. Can someone guide me on how to achieve this? The following code snippet is not working as expected: this.setState({ reviews[2].current: true }); Below is the comp ...

Steps for removing the bottom border for the last child in the Material UI Box Component

I have a Box Component where ListItems are wrapped. For each child, I have a border-bottom of 1px solid class set for the Box component, but I don't want it for the last child. How can I achieve that? {data.map((item, i) => { return ...

What is the best method for styling the "body" of multiple pages in a React.js application to prevent them from overlapping?

Hello everyone, After attempting different approaches in numerous ways, I have turned to the experts here who are sure to have the answer to this simple problem. The issue at hand is that when I try to apply background images and other properties to the ...

What is the best way to integrate an image gallery with twitter bootstrap?

I'm having trouble implementing an image gallery on my index page. Despite my efforts, I can't seem to achieve the desired behavior. Here's a snippet of my code: .container .row .col-md-8.col-sm-8.col-xs-8 - 4.times do |i| ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

JSFiddle showcasing the Bootstrap grid system

I'm having trouble implementing bootstrap's grid system on jsfiddle. Check it out on jsfiddle I've tried using the example from the bootstrap documentation: <div class="row"> <div class="col-md-1">.col-md-1</div> ...

In order to iterate through a 'IterableIterator<number>', you must either enable the '--downlevelIteration' flag or set the '--target' to 'es2015' or newer

While attempting to enhance my Slider, I encountered an error when utilizing TypeScript React within this Next.js project: "Type 'IterableIterator' can only be iterated through when using the '--downlevelIteration' flag or with a ...

An unusual CSS phenomenon with z-index

I've encountered a peculiar issue with my z-indexing. I have an image positioned relatively with a z-index of 1, and it should be above my navigation that is positioned absolutely with a z-index of -1. The problem is that upon page load, the image ap ...

Looking to showcase your logo prominently at the center of the page, flanked by two elegant

Is it possible to create a grid-like structure with dimensions 5.5-1-5.5? I would like to center a logo on the page with two lines on the left and right. (Please excuse my limited English skills) https://i.sstatic.net/cgjfS.png ...

Mastering the art of using transitions in conjunction with display properties

I'm trying to achieve a fade-in effect with the CSS property display:block. Here's my HTML code: <div>Fade</div> And here's my CSS code: div { display: none; transition: 2s; } div:hover { display: block; } Unfortunately, thi ...

Encountered an Unhandled Rejection error in react-planner when utilizing threejs: TypeError - url.lastIndexOf function is not recognized

Incorporating react-planner into my React application, I am utilizing a collection of 3D items that are stored in a catalog within my SRC folder, using MTL, OBJ, and texture files. However, upon switching to the 3D viewer, I encountered an error while att ...

Communicate with the parent component in React to either access data or pass data from parent to child component

Can you explain a method for passing data between components without using props? render() { return ( <Parent> <Child1> <Child2> </Parent> ); } In the context of components Parent and Child, how can the data genera ...

Width of ListBox Item

How can I adjust the width of items in my RadListBox that are being inserted programmatically to prevent multiple items from displaying on a single line? Currently, the items are added to the listbox in C# code like this: rlbAssigned.Items.Add(new RadLis ...

Making sure an image is visible using Webdriver

I'm facing an issue where an image disappears after reaching a certain width size. I'm unsure how to address this using Selenium. <img id="removeimg" class="col-md-5" src="images/abc-image.png" alt="abc"> Below is the corresponding CSS co ...

Choose all the items that share a specific hue?

How can I target all elements with a specific color? I need to update all text that has a color of #1a0dab to #00b0f4. ...

Expanding Page Width Using iPad CSS Styling

I am currently experiencing some difficulties with my webpage and its header layout when viewed on an iPad versus a desktop. Upon visiting on a computer, the images and header/footer are intended to extend 100% to the edges of the screen. However, when ...

Achieve scrollability for right column (div) using Tailwind CSS

I am having trouble getting the content in the right column to scroll vertically. Can someone please help me identify what I'm doing wrong here? <link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet"/> < ...

Experiencing an excessive amount of re-renders can lead to performance issues. React implements limits on the number of renders to avoid potential infinite

Would appreciate assistance in solving this code quandary. Whenever the "/" is removed before "about" and "id", it strangely does not generate any errors. import Navbar from "../components/Navbar"; import Footer from "../components/Footer& ...

Looking to save a CSS element as a variable

I am working on improving the readability of my code in Protractor. My goal is to assign a CSS class to a variable and then use that variable within a click method. element.all(by.css("div[ng-click=\"setLocation('report_road')\"]")).cl ...

Tips for ensuring the footer always stays at the bottom of the page

I'm having an issue with keeping the footer pinned to the bottom of the page. I haven't applied any specific styles to the footer, just placed it at the end of the content. Everything looks great until there's a page with minimal content, ca ...