Search code examples
reactjsreact-routerstyled-components

React-Router not correctly rendering Styled-Components Styles


The issue is that when I navigate to a 'Post', expanded screen, then use my browser to go back, it is not showing the correct CSS styles, it is using the styles from the expanded view, rather than the 'non-expanded' view. If I toggle a style on the Component using Inspect Element it fixes the issue immediately. I know I could probably circumvent this by adding a back button on the page, and I probably will, but what about the people who use the browser back button?

I am trying to use the same StyledComponent for different pages. Here is the code for my router

<Router>
      <Route
        exact
        path="/"
        render={() => posts.map((post, key) => <Post data={post} key={key} />)}
      />
      <Route
        exact
        path={`/posts/:post`}
        render={currentPath => renderCurrentPost(currentPath)}
      />
    </Router>

All that the second route does is find the correct post to render, then render it.

Here is my code for the specific styled component.

import Styled from 'styled-components';
const Title = Styled.h1`
    @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
    font-family: 'Roboto', sans-serif;
    font-style: medium;
    color: ${props => (props.expanded ? `white` : `#111111`)}
    font-size: ${props => (props.expanded ? `5vh` : `1.2em`)}
    margin: 0 0 0 0;
    align-self: flex-end;
    /* display: inline; */
    position: ${props => (props.expanded ? `relative` : ``)};
    top: ${props => (props.expanded ? `70%` : ``)};    
    left: ${props => (props.expanded ? `5%` : ``)};
     `;

export default Title;

I am using props heavily in these components as it will change the way it renders.

Here is the desired style that renders correctly when you first navigate to the landing page.Desired Style

Here is the non-desired styling that happens when you navigate back from a expanded post page using the browser back button.Non-Desire Style


Solution

  • I answered this myself by slowly removing each CSS line from my styled component to find the problem, which turned out to be this line of code

    padding: ${props => (props.expanded ? `` : `0 2% 0 10%`)};