1 April 2020

Conditionally applying inline styles in react js

  • Create Components folder under src folder
  • Add CSSConditionallyinline.js file and add below Code
import React, { Component } from "react";

class CSSConditionallyinline extends Component {
constructor() {
super();
this.state = { isRed: true };
}

render() {
const isRed = this.state.isRed;

return (
<div>
Conditionally applying inline styles
<p style={{ color: isRed ? "red" : "blue" }}>Example Text</p>
</div>
);
}
}
export default CSSConditionallyinline;
  • Open App.js file and update code as below\
import React from "react";
import ReactDOM from "react-dom";
import CSSConditionallyinline from "./components/CSSConditionallyinline";

function App() {
return (
<div className="App">
<CSSConditionallyinline />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:






No comments:

Post a Comment