1 April 2020

Complex Conditionally applying CSS classes in react js

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

class CSScomplexconditions extends Component {
getClass(someInput) {
switch (someInput) {
case "1": {
return "class1";
}
case "2": {
return "class2";
}
case "3": {
return "class3";
}
}
}
render() {
return (
<div>
complex Conditionally applying CSS classes
<p className={this.getClass("2")}>Example Text</p>
</div>
);
}
}
export default CSScomplexconditions;
  • Add CSScomplexconditions.css file and add below Code
.class1 {
background-color: red;
}
.class2 {
background-color: blue;
}
.class3 {
background-color: orangered;
}
  • Open App.js file and update code as below\
import React from "react";
import ReactDOM from "react-dom";
import CSScomplexconditions from "./components/CSScomplexconditions";

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

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

Output:



No comments:

Post a Comment