Tag Error: React JSX Style Tag Error on Render
CssReactjsCss Problem Overview
This is my react render function
render:function(){
return (
<div>
<p className="rr">something</p>
<style>
.rr{
color:red;
}
</style>
</div>
)
}
This gives me this error > "JSX: Error: Parse Error: Line 22: Unexpected token :"
What's wrong here? Can I embed full normal css into a react component?
Css Solutions
Solution 1 - Css
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.
Solution 2 - Css
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>
)
However there is absolutely no good reason to do this at all.
Solution 3 - Css
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
Solution 4 - Css
This can be done by using backtick "`" as below
return (<div>
<p className="rr">something</p>
<style>{`
.rr{
color:red;
}
`}</style>
</div>)
Solution 5 - Css
"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
Solution 6 - Css
-
Create a function to handle inserting the style tag.
-
Add the CSS you want to a string variable.
-
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> ) }
Solution 7 - Css
This is what I did:
render(){
var styleTagStringContent =
".rr {"+
"color:red"+
"}";
return (
<style type="text/css">
{styleTagStringContent}
</style>
);
Solution 8 - Css
import styled from 'styled-components;
return (
<div>
<Test>something</Test>
</div>
)
Next Step:
const Test = styled.p`
color: red
`;