Adjust Style based on props with Styled Components

Sara Vieira
InstructorSara Vieira

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

We are going to learn how to add styles to a react component using the styled-components library.

We will get a list of people and give a different color and background color when their position in the list is an even number, like zebra stripes.

Inside of the backticks for our custom styled element, we can interpolate and add in a function that checks if the name in our array is at an even position, it’ll change the text color to white and the background color to black.

Instructor: [0:00] I have this list of people, which are 1, 2, 3, 4, 5 names. I have this person, which is already a styled component. I want to check if the number is even.

[0:11] For example, Sara is 1 and Alex is 2, which means that it's an even number in the list. Basically, I get the index of the array. I add it 1, because our array starts in , modulus, and then see if it's . If this returns true, then it is even.

[0:27] What I want to do is kind of a zebra stripe type of thing. To do that, I need to style this component based on the props. How do we do that?

[0:36] As you can see, the styled component already works with backticks. The way that we do is how we interpolate with backticks.

[0:45] I am going to do this, and everything that we use here gets all the props. I am going to do this. Let's do something. Let's say if props.even I want to do something. I want to return a different value than color gray. I can say, "Return and open backticks again just 1, not 3." I can say, "Color white."

[1:14] These two, which is number 2 and number 4, are hidden because the background isn't a visible color for white. Let's [inaudible] background of black. Now we have this zebra stripe effect that we were able to do.

[1:29] The idea here is that in here I pass a prop called even which is either true or false based on this math that I have here. In here, I check all the props. I check if the even prop is true. If it is, it means that it is an even number, it is an even list item and I want to pass different CSS.

[1:48] You don't want to write all of this every time you want to check something. One thing that we can do is minimize this a lot by just checking. If we have the props, we can say props.even and we just pass the text.

[2:04] This means if props.even is true, you render this or in this case you return this. Let me just add something else so that you can see that it's the same. List all of none and only these ones will have a list all of none. This is how you can style these components based on the props that you pass it in your React components.