score:62

Accepted answer

JSX is only a small extension to javascript, it's not its own full blown templating language. So you would do it like in javascript:

return (
  <div>
    <p className="rr">something</p>

      <style>{"\
        .rr{\
          color:red;\
        }\
      "}</style>
  </div>
)

http://jsfiddle.net/r6rqz068/

However there is absolutely no good reason to do this at all.

score:-2

import styled from 'styled-components;

return (
 <div>
  <Test>something</Test>
 </div>
)

Next Step:

const Test = styled.p`
  color: red
`;

score:3

This is what I did:

render(){
    var styleTagStringContent = 
    ".rr {"+
       "color:red"+
    "}";
    return (
      <style type="text/css">
        {styleTagStringContent}
      </style>
);

score:7

  1. Create a function to handle inserting the style tag.
  2. Add the CSS you want to a string variable.
  3. Add the variable to the returned JSX inside of your <style> tag.

    renderPaypalButtonStyle() {
        let styleCode = "#braintree-paypal-button { margin: 0 auto; }"
        return (
            <style>{ styleCode }</style>
        )
    }
    

score:9

"class" is a reserved word in JavaScript. Instead use "className".

Also, you have to remember you're using JSX, not HTML. I don't believe jsx will parse your tags. A better approach is to create an object with your styles then apply that as the style (see below).

var styles = {
  color:"red";
}

return (
  <div>
    <p style={styles}>something</p>
  </div>    
)

score:13

This can be done by using backtick "`" as below

return (<div>
        <p className="rr">something</p>


          <style>{`
            .rr{
              color:red;
            }
          `}</style>
  </div>)

score:27

Inline-styles are best applied directly to the component JSX template:

return (
  <div>
    <p style={{color: "red"}}>something</p>
  </div>
);

DEMO: http://jsfiddle.net/chantastic/69z2wepo/329/


Note: JSX does not support HTML syntax for the style attribute

Declare properties in using camelCase property names, e.g.,

{ color: "red", backgroundColor: "white" }

Further reading here: http://facebook.github.io/react/tips/inline-styles.html

score:107

Easy to do with es6 template strings (which allows line breaks). In your render method:

const css = `
    .my-element {
        background-color: #f00;
    }
`

return (
    <div class="my-element">
        <style>{css}</style>
        some content
    </div>
)

As for use case I'm doing this for a div with some checkboxes that I'm using for debugging, that I would like to contain within one file for easy removal later.


Related Query

More Query from same tag