How can I apply CSS to a child tag based on its parent tag in a React component?

import React from 'react';
const style = {
    h2 : {
        fontSize: '20px';
        color: 'black';
    } & span: {
       color: 'white';
    }
}
const Main = () => {
    return (
        <h2 style={style}>Hello<span>Test</span></h2> 
   );
}
export default Main;

Note: The styling can be dynamic and versatile. The h2 tag acts as the parent element, allowing the applied style to cascade down to the child span tag as well for consistent formatting.

Answer №1

When it comes to styling in JSX, the style property functions similarly to HTML's style attribute. Both of these accept only CSS properties, excluding selectors, pseudo-elements, or pseudo-classes.

Utilizing the Style Property

To improve readability and maintain clear separation of styles, consider the following approach:

const h2Style = {
  fontSize: '20px';
  color: 'black';
}
const spanStyle = {
  color: 'white';
}

const Main = () => {
    return (
        <h2 style={h2Style}>Hello<span style={spanStyle}>Test</span></h2> 
   );
}

Alternatively, for a more organized structure:

const styles = {
  h2: {
    fontSize: '20px';
    color: 'black';
  },
  span: {
    color: 'white';
  }
}

const Main = () => {
    return (
        <h2 style={styles.h2}>Hello<span style={styles.span}>Test</span></h2> 
   );
}

If you prefer defining styles externally, consider using CSS/SCSS:

import "./your-css.css";

const Main = () => {
    return (
        <h2 className="title">Hello<span>Test</span></h2> 
   );
}

Where .your-css.css would contain:

.title {
  fontSize: '20px';
  color: 'black';
}

.title span {
  color: 'white';
}

For a more sophisticated approach using CSS-in-JS with styled-components:

import React from 'react';
import styled from 'styled-components';

const Title = styled.h2`
  fontSize: '20px';
  color: 'black';

  span {
    color: 'white';
  }
`;

const Main = () => {
    return (
        <Title>Hello<span>Test</span></Title> 
   );
}

export default Main;

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

Incorrect form element style is only visible when contained within an unstyled HTML Details tag

A demonstration form control extracted from the Bulma CSS framework documentation performs as anticipated with Bulma 0.7.2 (most up-to-date version at the time of writing). However, when this form is contained within a standard html <details> tag, t ...

Cease the use of the jQuery.css() method

Does anyone know how to halt the jQuery css() function? I've successfully used the jQuery.stop() function to pause the animate() function, but I'm unsure about stopping css(). Any help is appreciated. Thanks! ...

Full-width sub menu within the menu

I'm trying to make a sub menu appear below my main menu that is the same width as the main menu, which has a fixed width. I want the sub menu to adjust its width based on the number of links it contains. Is this even possible? Here's the code I h ...

What is the best way to determine if an array of objects is present in the state of a React

Currently, I am in the process of developing a dynamic form using React JS. One aspect of my form involves an input field with a limit of 10 characters. To enhance the cleanliness of my code, I have constructed an object and utilized mapping to streamline ...

How to Align Paypal Button in the Middle of a Table Cell within a Concealed Form Using HTML and

Currently, I am in the process of developing a payment page that enables payments through Paypal using Instant Payment Notification. The initiation of this process involves sending a POST request to Paypal via a submit button along with multiple hidden for ...

Working with data filtering in React.js

Imagine having a list of records that you want to filter based on the user's selection from a select box. You can find all the details in this JSFiddle. http://jsfiddle.net/reactjs/69z2wepo/ For instance, if the user chooses 1-10, only numbers betwe ...

Ways to achieve a consistent font style in a Photoshop design

After recently starting to dabble in Photoshop, I managed to create a cool text effect a few days ago. Now, I'm looking to achieve the same effect and apply it to a different image. The text contains a date that I want to update, but I can't reme ...

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

Having trouble with Firefox not recognizing the linear gradient color in my CSS3 code

I'm working on implementing a linear gradient background using CSS, but I'm facing an issue with Firefox not displaying it correctly. body { height: 100%; /*background-color: #F0F0F0;*/ background-repeat: repeat-x; /* Safari 4-5, Chrome 1-9 */ ...

When employing a CSS combination of `position: fixed;` and `display: flex;`, the upper portion of the inner element is excised and out of reach

I'm currently working on a fullscreen modal and facing an issue with centering the content vertically when it is smaller than the screen. Additionally, I need the content to start at the top and allow scrolling when its height exceeds the container&ap ...

Is it possible to enable CSS margins to collapse across a fieldset boundary in any way?

One interesting CSS behavior is that adjacent vertical margins typically collapse into one another. In other words, the space between elements will be equal to the larger margin instead of the sum of both margins. Interestingly, fieldset elements do not f ...

Guide on how to show an icon in Meteor when a link is clicked

Is there a way to display a viewed icon upon clicking a link in Meteor? On my list of jobs page, when a user clicks on a job, they are taken to the description page. I would like to add an icon to the post indicating that the user has viewed it. ...

"Utilize React Native to access the gallery with the help of an

//I encountered an issue while trying to open the gallery using the react native image picker import React, { useState } from 'react' import { launchCamera, launchImageLibrary } from 'react-native-image-picker' import * as ImagePicker ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Styling for Print Media: Adjusting the horizontal spacing between inline elements

I have been developing a custom AngularJS point-of-sale (POS) system that requires printing receipts upon completing a sale. To achieve this, I am using ng-print to print out a sales summary displayed within a specific div element after hiding all other un ...

Tips for resolving the issue of npm start not functioning correctly following the use of npx create-react-app framework

npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23574c474c4b504e42574537464f074b5b5b2b1bfb4b7b6edb1acacb1">[email protected]</a> start: `react-scripts start` npm E ...

Personalizing a class specifically for error messages within the jQuery Validation plugin

When using the jQuery Validate plugin, is it possible to set a separate class for the error message element without affecting the input element's class? ...

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

Position the form / delete button in alignment with the rest of the buttons

I have a table with options at the end like View, Edit, and Delete. I need the Delete button to be inside a form so that I can POST the delete request. However, my button/form is not aligning on the same line as expected. I have tried using the form-inlin ...

Upgrade from react-router v5 to v6 for dynamic navigation between tabs

I am facing issues while updating to react router v6 in my shared component with tab navigation. The URL structure is as follows: domain.com/home/:tab domain.com/settings/:tab I have a base route like home, settings,... and the tab name is appended at t ...