I'm trying to add a style to the active link with styled components.
I have a navbar and depending on which link is currently active, the respective link will have a style added to it
Thanks
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { bool } from 'prop-types';
import StyledSidebar from '../../styles/header/styled.sidebar'
import StyledLink from '../../styles/header/styled.links'
export default function Sidebar({ open }) {
const router = useRouter()
return (
<StyledSidebar open={open}>
<div>
<ul>
<StyledLink><Link href="/" className={router.pathname == "/" ? 'active' : ''}>HOME</Link></StyledLink>
<StyledLink><Link href="/destination" className={router.pathname == "/destination" ? 'active' : ''}>DESTINATION</Link></StyledLink>
<StyledLink><Link href="/crew" className={router.pathname == "/crew" ? 'active' : ''}>CREW</Link></StyledLink>
<StyledLink><Link href="/technology" className={router.pathname == "/" ? 'active' : ''}>TECHNOLOGY</Link></StyledLink>
</ul>
</div>
</StyledSidebar>
)
}
Sidebar.propTypes = {
open: bool.isRequired,
};
Check this https://codesandbox.io/s/exciting-kilby-eb3pj?file=/src/App.js:0-584 link where you see this logic live
Pass the props to styled-components as normal props restructure and use it for conditionally render the styles
import styled, { css } from "styled-components";
// props which are received are destructured
const Button = styled.button(
({ someprops }) => css`
${console.log(someprops)}
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
// Conditionally render the styles inside style
color: ${someprops === "root" ? "red" : "green"};
border: 2px solid ${someprops === "root" ? "red" : "green"};
`
);
export default function App() {
return (
<div>
<Button someprops="root">Themed</Button>
</div>
);
}