acenturyandabit
acenturyandabit

Reputation: 1408

React style element descendant selector

I want to use the direct descendant CSS selector in a React inline style element:

 <style>{`
  .something>div{
    color: blue;
  }
`}</style>

This is working fine on dev but in prod, React (un)helpfully converts the > into a gt;, screwing up my CSS.

How can I do a direct descendant in a React inline style element?

Alternatively, how can I get React to treat the innerHTML as literal?

I have a React app with multiple files and pages using Gatsby, which is notorious for not allowing multiple different CSS for different pages. I'm also using nested React components, so giving the nested components classes is not an option without modifying node_modules.

Upvotes: 0

Views: 3129

Answers (2)

acenturyandabit
acenturyandabit

Reputation: 1408

If you're insisting on using child selectors in CSS with style tags, you can use the dangerouslySetInnerHTML property of a jsx (in this case, style) element:

<style dangerouslySetInnerHTML={`
div>p{
 color:blue;
}
`}/>

Upvotes: 1

RiverTwilight
RiverTwilight

Reputation: 716

Try styled-components, you can write style like native css with it. e.g.

import styled, { css } from 'styled-components'

const ToTop = styled.button`
    position: fixed;
    right: 10px;
    bottom: 10px;
    polyline {
        stroke:#000;
        ${otherStyles}
    }
    &: hover{
        background: #dcc9c9;
    }
`

export default () => (
    <ToTop />
)

About InnerHTML, see this doc

Upvotes: 2

Related Questions