How To Style A React Component? - part 5

←  Add Props to Functional Component - part 4

react js tutorial - Add CSS Style to React Component With Example

Adding styling to CSS in react is not new concept just the standard rules but we still need to understand the idea of JSX styling and how it operates in the component.

You can create stylesheet for each component or you can put all your CSS code in a single file and name it for example styles.css. It is entirely up to you which method you like. If you asked me I will recommend you use single file for small project and use component based if it is big.

Remember the three rules for adding styling to HTML:

  •  Inline Style
  • Internal Style
  • External Stylesheet

That is exactly what we can accomplish with react, but in JavaScript manner.  I'll demonstrate three ways we applied styles to the component using React. Let's take each one in turn.

React Inline Style 

We may add CSS styles directly in JavaScript using the style attribute. For inline style, we use double curly braces {{ }} because JavaScript expressions are placed inside curly braces and JavaScript objects also utilise curly braces, and add a comma if you have additional CSS properties.

<h1 style={{color:'white', backgroundColor:'steelblue'}}>Hello World!</h1>

In the above example we use camelCase for multiword property "backgroundColor" rather than "background-color" or we will use "marginTop",  prefixed properties follow the same criteria, but other than the ms vendor prefix, they must also begin with a capital letter. For ex - WebkitTransition, msTransition

Basically key is camel case version and the value is usually a string

React Object Variable

The second way is similar to internal. We assign the variable and create an object as the variable's value, and refer the JavaScript object to the style attribute as JavaScript expressions into the JSX. If you have some dynamic styling, you can utilise this way.

const HeaderStyle = {
    backgroundColor: 'steelblue',
    padding: '1rem',
    color: '#fff',
    marginTop: 0
  }
<h1 style={HeaderStyle}>Hello World!</h1>

Please keep in mind that adding semicolon to an object will result in an error. Additionally, if you wish to add a unit like rem, pt, or %, you must include it as a string because if you don't and supply it as a number, it append px automatically.

CSS Stylesheet

There are two ways to style an element: by adding a class attribute or by utilising the style attribute. Classes should always be preferred for styling, only properties can be written directly if class can't handle it.

So, the other method I mentioned using class, the most popular way, using the external style sheet. We add class attribute as className, camelCase, remember it is JSX not simple HTML, where we pass DOM element.

Whether the code is contained in a component or a separate style sheet, we must import it into our file in order to apply it to an element. Let's start with styles.css,  then paste all of the code in this file and import it into the App component.

// In Styles.css
body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px; 
 }
.container {
  max-width: 500px;
  margin: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  background-color: aliceblue;
}
button {
  display: inline-block;
  border: none;
  outline: none;
  font-size: 16px;
  font-weight: 700;
  color: #000;
  width: 100%;
  padding: 1rem;
  margin-top: 2rem;
  cursor: pointer;
}

Because we use a single file for all components, simply import it at the top of the App.

import './styles.css'

Let's use the second strategy, example of a component based, create the StylesComponent.css file in the 📁component folder and put the code for the only style you need to utilise in this single component. 

// in StylesComponent.css
.container {
  max-width: 500px;
  margin: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  background-color: aliceblue;
}
button {
  display: inline-block;
  border: none;
  outline: none;
  font-size: 16px;
  font-weight: 700;
  color: #000;
  width: 100%;
  padding: 1rem;
  margin-top: 2rem;
  cursor: pointer;
}

Now import this file at the top of MyComponent.

import './StyleComponent.css'

React CSS Class

On the basis of the component's stats or properties, we can also apply class conditionally. Using the props example, let's pass down the props active and set its default to false on the MyComponent.

.active {
	background-color: steelblue;
 }
 .default {
 	background-color: #d1d1d1;
 }
function App() {

    return <MyComponent active={false} />
 }

Now I can utilise the props in the component as a parameter, define the variable className in the function body, and use the conditional operator to set the condition to true or false. The variable will then be used as the JavaScript expression for our class name attribute in JSX.

const MyComponent = (props) => {
	const className = props.active ? 'active' : 'default';
    
    return <button className={className}>Add List</button>

 }

The button should now appear in default, when you look at the browser screen. Go back to your App component and pass the property active as true to make the button active and visible in steelblue. 

function App() {

    return <MyComponent active={true} />
 }

To put it simply, we determine from the value of props whether it is true or false, and then give that value to the className attribute.

If we need to define many classes, we can utilise template literals and then in MyComponent, we can supply our second class name shape. 

Now let's give our button a shape.

.shape {
	border-radius: 10px;
 }
<button classsName={`${classname} shape`}>Add List</button>

Now if you look at the screen, the outcome will alter, the button is now somewhat rounded. We did this by changing the value of the class name attribute to a template literal using backticks and putting curly braces around the className, which we specified in the prior example, because it is a variable.

Our two classes have been used, and this is how classes are used when using standard style sheets.

Conclusion

React may be styled in a variety of ways using CSS. Inline styling, style object variables, a CSS style sheet, and a React class are all covered in this tutorial. Don't get into a debate about which way is superior because we use these strategies occasionally and only when it makes sense.

Please share any thoughts you may have about this post. Have fun Coding!

0 Comments:

Post a Comment