Home  >  Q&A  >  body text

How to add css of child tag based on parent tag in React?

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: can be dynamic. H2 is the parent tag and I have applied the style in the same tag and I want it to apply to the child tags as well ().

P粉258788831P粉258788831423 days ago538

reply all(1)I'll reply

  • P粉826283529

    P粉8262835292023-09-14 12:15:28

    JSX style attributes are similar to HTML style attributes. Both the style attribute and attribute only accept CSS properties. Therefore, the use of selectors, pseudo-elements or pseudo-classes is not allowed.

    Using style attributes

    Replace the following:

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

    and:

    const h2Style = {
      fontSize: '20px';
      color: 'black';
    }
    const spanStyle = {
      color: 'white';
    }
    
    const Main = () => {
        return (
            <h2 style={h2Style}>Hello<span style={spanStyle}>Test</span></h2> 
       );
    }

    or clearer:

    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> 
       );
    }

    However, since you only want to define styles for h2 elements, we have more options:

    CSS/SCSS

    Using CSS on separate files:

    import "./your-css.css";
    
    const Main = () => {
        return (
            <h2 className="title">Hello<span>Test</span></h2> 
       );
    }

    Among them, the .your-css.css file contains

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

    Even nested (if you use a preprocessor like .scss)

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

    CSS-in-JS

    Considering a more "React" solution, we could use CSS-in-JS like styled-components Learn more

    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;

    reply
    0
  • Cancelreply