What is the best way to change the className of an extended component?

I'm currently facing a challenge in positioning this component differently on a specific page. Despite providing it with another className property, it seems to only take on the original class's styling that was assigned during the component declaration.

Component:

import React, { Component } from 'react';
import styles from './label.css';

class Label extends Component {
  render() {
    return (
      <div className={styles.labelClass} />
    );
  }
}

export default Label;

Page where I want to adjust its position:

import React, { Component } from 'react';
import styles from './page.css';
import Label from '../common/label.jsx';

class Page extends Component {

  render() {
    return (
      <div>
          <Label className={styles.positionLeft} />
      </div>
    );
  }

}

export default Page;

Typically, I would resolve this issue with custom styling, but due to the necessity of using media queries, this approach isn't feasible in this scenario.

Answer №1

Because <Label> is a custom component, you need to manually pass the className prop down.

This scenario presents a perfect opportunity to utilize default props!

class Label extends Component {
  render() {
    return (
      <div className={this.props.className} />
    );
  }
}

Label.defaultProps = {
  className: styles.labelClass
}

By doing this, if no className is specified for Label, it will default to using the labelClass style. Otherwise, it will use the provided prop.

Answer №2

By incorporating an additional optional property called customClass into the component, I was able to resolve the issue.

Description

import React, { Component } from 'react';
import styles from './description.css';

class Description extends Component {
  render() {
    return (
      <div className={styles.descriptionClass + ' ' + this.props.customClass} />
    );
  }
}

export default Description;

Section

import React, { Component } from 'react';
import styles from './section.css';
import Description from '../common/description.jsx';

class Section extends Component {

  render() {
    return (
      <div>
          <Description customClass={styles.alignmentCenter} />
      </div>
    );
  }

}

export default Section;

Answer №3

To make use of the className property from Label's props, you should specifically reference it like so:

import React, { Component } from 'react';
import styles from './label.css';

class Label extends Component {
  render() {

    let { className } = this.props

    if (!className) {
      className = styles.labelClass
    }

    return (
      <div className={className} />
    );
  }
}

export default Label;

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

What are the best ways to enhance performance when making multiple require() calls?

I am in the process of developing a bot for my company's Mattermost server (similar to a Discord bot). Each command for the bot is housed in its own file, making it easier to manage and maintain. When a user wants to execute a command, they must send ...

Creating a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

Is there a way to prevent my smartchatbox from covering my fixed top navbar?

Click here for more information I am seeking assistance. Your help is greatly appreciated. The question's heading reveals all you need to know. All you have to do is resize your browser, scroll down, and the answer will become apparent. ...

Steps to retrieve all tags from HTML content and display them in a text box

Within a textarea with the id of "textArea1", I have embedded webpage HTML source code. This particular HTML code includes various instances of "p" tags. My objective is to compile a list of all the p tags that are inside the mentioned textarea. ...

Straining data in text input fields using bootstrap

Looking for a way to filter data with bootstrap/jquery without using tables, just div rows and columns. Check out an example of how my form looks Here's a snippet of my code: <div class="row"> <div class="col-md-4"> <input class= ...

Exploring Virtual Reality with the Oculus Quest2 and Three.js

Currently, I am working on a project using Oculus and three.js to create a virtual reality experience. To test the functionality, I decided to try out the official sample provided. Here is the link to the official sample. My intention was to access the s ...

Extract the content of an element and incorporate it into a script (AddThis)

HTML: <div id="file-section"> <div class="middle"> <p class="description"> Lorem ipsum... </p> </div> </div> jQuery: var share_on_addthis = { description: $('#file-section ...

The grid item's content is spilling out of its container

I am experiencing an issue with a simple grid where the content of two grid items is overflowing and not staying within their designated areas. Below is the code snippet I am using, which was partially inspired by this post: body{ background-color ...

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

Internet Explorer is unable to support the 'stop' property or method for this object

Upon clicking the submit button, I encountered an error message stating "Object doesn't support property or method stop" in Internet Explorer. However, despite this error, the data was successfully added to the database. Below is the code snippet: f ...

Generate a dropdown menu with dynamic options populated from an API by adding an input type select element dynamically

Greetings! I am working on designing a decision tree that dynamically generates options based on user selections and API responses. When a user chooses a reason option, the corresponding reasons are fetched from the API and displayed in a select dropdown. ...

When using the next/link redirect feature, it is recommended that the page be set to scroll to the top

I'm working on a Next.js website with links in the footer. When I click on one of these links, the page first redirects to the new page with the current position scrolled down and then scrolls back up. However, I want it to default to the top of the p ...

Using Material UI with React: Strategies for Combining Multiple External Makestyles

I am looking to merge multiple external makestyles so that I can better organize the styling for each component. While a single makestyle works well, the file length is becoming an issue. I came across this concept in the Material UI documentation, but un ...

Problem with the visibility of the drop-down menu when hovering over it

I am currently developing a ReactJS application using reactstrap. One of the components I have created is a dropdown with submenus nested inside. My goal is to make the submenus appear when hovering over the dropdown, and if there are multiple dropdowns ( ...

Control the options of the Select menu using ajax

Consider having two dropdown menus <select id=first> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</opti ...

`Using Rollup to combine local typescript files into a single main bundle`

I'm currently working on developing an npm module that is intended for use in web browsers. For this project, I have chosen to utilize TypeScript and Rollup as my tools of choice. Here is a snippet of my tsconfig.json: { "compilerOptions": { " ...

Modifying appearance following an Axios request to a specific URL

Hi there, I've encountered a strange issue while fetching data from axios and attempting to implement pagination. The styling changes when I hover over the select input element. Let me illustrate this with an example: Check out this sandbox link Hov ...

Is there a way to use JavaScript to retrieve a list of files that were loaded by the browser during the last request

I'm just starting out in the world of JavaScript and I have a query: is there a method to retrieve a list of files that were loaded by the browser during the last request? To clarify, when a browser loads a webpage, it not only downloads the HTML fil ...

Adding alpha or opacity to the background image will give it a unique and

Is there a way to darken the background image while keeping the text color the same? Check out this code snippet on JSFiddle div { display:block; background:url('http://placehold.it/500x500') 0 0 no-repeat; background-color:rgba(0 ...