Add dynamic styling
One of the great features of CSS-in-JS is that it allows us to modify the styling of elements dynamically. Let's take a look at how we can do this.
You will recall that in an earlier lesson in this section we added an 8px wide border to the bottom of our header. We'll use that to indicate whether we're on a list page, a post page, or a page, erm..., page 🤷🏻‍♂️ by changing the colour of the border depending on which type of page we're on.
To do this we'll add an isPostType prop to the <Header> component.
1
// File: /packages/my-first-theme/src/components/index.js
2
​
3
// ...
4
<Header isPostType={data.isPostType}>
5
// ...
Copied!
This prop gets passed to a function that we add to our CSS that conditionally checks the boolean value passed in to determine what colour the border should be, i.e. either green in the case of a post or page, or maroon in the case of a list.
We're no longer using JSX here so we need to prepend the function with a $ sign, and we also need to use the ternary operator - we cannot use if...then...else in JavaScript embedded within a template literal.
1
// File: /packages/my-first-theme/src/components/index.js
2
​
3
// ...
4
const Header = styled.header`
5
background-color: #e5edee;
6
border-width: 0 0 8px 0;
7
border-style: solid;
8
border-color: ${(props) => (props.isPostType ? "lightseagreen" : "maroon")};
9
`
Copied!
Let's extend this to get a different colour for pages to further distinguish them from posts. We'll add the isPage prop to our header, and extend our conditional.
Note that here we have a ternary operator as the ifTrue expression within our original ternary operator!!! We've enclosed the nested statement in parentheses for further clarity.
1
// File: /packages/my-first-theme/src/components/index.js
2
​
3
// ...
4
<Header isPostType={data.isPostType} isPage={data.isPage}>
5
// ...
6
​
7
// ...
8
const Header = styled.header`
9
background-color: #e5edee;
10
border-width: 0 0 8px 0;
11
border-style: solid;
12
border-color: ${ props => props.isPostType ? ( props.isPage ? 'lightsteelblue' : 'lightseagreen' ) : 'maroon'};
13
`
Copied!
Now if we navigate to Home the header has a maroon border (as it's a listing page), if we click on one of the posts the post page has a green border, and if we navigate to About Us, (which is a page rather than a post) the header has a blue border.
The styling for the border is applied dynamically depending on the type of page that we're on, which is determined by the isPostType and isPage boolean properties found in the data for the current URL.
The 'isPostType' property is true for posts
The 'isPage' property is true for a pages
Awesome, our site is starting to look pretty good now! 👌
Frontity in the browser - listing
Frontity in the browser - post
Frontity in the browser - page
Check you're on the right track by comparing your changes with the ones in this commit.
Last modified 5mo ago
Copy link