In the last lesson, we have enable CSS module by ejecting the configuration fine tuning it and then importing classes from the CSS file and used them.
Pseudo selectors are important in App.js where we assign a button style. Now we will no longer will use the style propert on the button, so will remove it from there also the define properties assigned to it..
... return ( ... <button style={style} onClick={this.togglePersonsHandler}> Switch Name </button> ... ); ...
After that will create a .button or by applying css rules i.e. (.App button { ... }) css class in App.css file.
.button
.App button { ... }
.App { text-align: center; } .red { color: red; } .bold { font-weight: bold; } .App button { border: 1px solid blue; padding: 15px; background-color: green; font: inherit; color: white; cursor:pointer; }
And now when you run the application you can find new styles are applied and no longer inline css is bind as you can find by doing inspect elements. Now, of course, we still want to able to set the button to Red and we want to be able to see as hovering over it.
:hover
So let me add :hover to the button with normal css
... .App button { ... } .App button:hover { background-color: lightgreen; color: black; }
And now lets handel the red case. Now for that I will simply add Red class and of course the hover part also
... .App button { ... } .App button:hover { ... } .App button.Red { background-color: red; } .App button.Red:hover { background-color: salmen; color: black; }
Now all we need to do is conditionally add the Red class to the button if we need it so back in App.js
So in App.js we simply need to bind className off the button. so will do it inside the Render() method. Prior to the if statement, we have a default button class which is null let’s say or simply an empty string.
Render()
render() { ... let btnClass = ''; ... }
then inside that if statement where I assignned persons.
import AppClasses from './App.css'; ... if (this.state.showPersons) { ... btnClass = AppClasses.Red; // also work for nested class } ... return ( ... <button className={btnClass} onClick={this.togglePersonsHandler}> Switch Name </button> ... );