Saturday 17 April 2021

Part 14 : Apply CSS Dynamically in React

In this and upcoming few article I will show different ways of using CSS in react application. I have added style variable in app.js file at line number 29 shown below. CSS applied to button dynamically and based on employee is visible or nor, color of button gets change. If showEmployees variable is true, color of toggle button is blue else orange at line number 51. Style applied to button at line number 57.
We can call it as inline style but style variable is nothing but JavaScript variable and JSX convert it into inline CSS in background. For more detail launch browser window and press F12 to view developer mode. Highlighted is the inline style rendered properly on browser.
If you notice at line number 55, I’m using ClassName=’App’ and App class is referenced from external CSS file imported at line number 2..
Open terminal window in VS code, select new command prompt and navigate till project path and run application using npm start command.
Initially toggle button should be in blue color and once you click on toggle button, color of button should change from blue to orange.

Apply CSS Style using external CSS file: Let’s see how to apply CSS class from external file in more details in react application. CSS style defined in CSS file (App.css) and reference of this css file mentioned in App.js file. Open App.css file and update below highlighted code from line number 5 to 11.
Open App.js file and add code available at line number 36 and 58.
I have created JavaScript variable which holds CSS class name declared in app.css file shown in above screen and at line number 58 Classname holds created JavaScript variable which contains CSS class name separated with space using join function of JavaScript(line 36).
With above change run application and observe changes on browser.
Apply CSS dynamically: Modify below piece of code in app.js function from line number 36 to 41 and at line number 62. I have used if else statement and based on employee count it apply CSS style to header.
Run application and click on card to delete card and text color and font gets change for header.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home