Search code examples
reactjsstyling

How to write inline styles for html tags in React?


I want to set a header tags styling froma top level component, something like this:

 <div style={{
        ['h2']: {
            backgroundColor: 'red'
        }
    }}>
        <h2>test</h2>
    </div>

Where 'test' would have a red background, I can't do this any other way as in my use case I get a JSX Element as a variable that contains a h2 element, I cannot emphasise enough the top example with is overly simplified and I cannot access the h2 tag in any obvious way in the real use case where I have to do something like {props.children}


Solution

  • You could even use styled components - this gives you more flexibility.

    import React from "react";
    import ReactDOM from "react-dom";
    import styled from 'styled-components';
    
    const Div = styled.div`
     background-color: red
    `;
    
    
    const App = () => (
      <Div>
        <h2>Test</h2>
      </Div>
    );
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);