I am trying to set inline styles in my React application. In this case, for a span:
This is the way how you can define and use inline style with react.
/**
* Style definitions.
*/
const STYLE = {
infoColor: {
color: 'green'
},
warningColor: {
color: 'orange'
},
errorColor: {
color: 'red'
}
};
/**
* Component
*/
class Welcome extends React.Component {
/**
* Rendering into the DOM.
*/
render() {
return (
<div>
<h2 style={STYLE.infoColor}>Welcome!</h2>
)
}
}
don't wrap the {{}} in double quotes or string
JSX and html are different things and we have a little different syntax to add inline css in jsx I would recommend to go through whole documentation for better understanding https://www.w3schools.com/react/react_css.asp
There some ways to set style for React Components.
https://facebook.github.io/react/docs/context.html
https://github.com/facebookincubator/create-react-app
using className="your-class-name"
using style={css_object}
or style={{color: this.props.color}}
https://jscomplete.com/repl
stylesheet.css
import './styles.css';
/*
.classname-color{
color: "red";
background: "#0f0";
}
*/
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span className="classname-color">{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
.classname-color{
color: "red";
background: "#0f0";
}
// <span style={styles}>
const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style={styles}>{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
// <span style={{color: styles.color}}>
const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style={{color: styles.color}}>{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
Use "styles" prop instead of style
<span className="myClass" style={{float : 'left', paddingRight : '5px'}} > </span>
JSX AND HTML are different:
In HTML it is
<div style="background-color: red;"></div>
In JSX you write
<div style={{ backgroundColor: 'red' }}></div>
Conditional inline formatting are different in both.