Reputation: 16163
I am using a variable to conditionally show different JSX and it isn't using the styling that is defined in its parent function. How can I make that work?
You can see a demo here: https://codesandbox.io/s/styled-jsx-example-e6tf6
import React from 'react'
function StyledJsxTest({ isLoggedIn, areButtonsVisible }) {
function renderButtons() {
const buttons = isLoggedIn ? (
<a className="button" href="/dashboard">Dashboard</a>
) : (
<>
<a className="button" href="/signIn">Log In</a>
</>
)
return (
<div>
<div>
<a className="button" href="/dashboard">Test</a>
{buttons}
</div>
<style jsx>{`
.button {
background-color: blue;
color: white;
padding: 20px;
margin: 10px;
}
`}
</style>
</div>
)
}
return (
<div>
<h1>This is a headline</h1>
{renderButtons()}
</div>
)
}
export default StyledJsxTest
The buttons in this chunk of code are not getting the . button
rule. How can i get those to work?
const buttons = isLoggedIn ? (
<a className="button" href="/dashboard">Dashboard</a>
) : (
<>
<a className="button" href="/signIn">Log In</a>
</>
)
Upvotes: 2
Views: 607
Reputation: 1411
Actually, I think there is no problem running the code and getting the style of .button class.
However, I might write it somehow different; but, it works !
The problem maybe of your browser cache
or something !
Upvotes: 0
Reputation: 19762
My guess would be that you forgot to add styled-jsx/babel
to your .babelrc
configuration.
Working example:
Upvotes: 1
Reputation: 11
I think the following should do what you're after:
import React from 'react'
function Button(props) {
return (
<a
{...props}
style={{
backgroundColor: 'blue',
color: 'white',
padding: '20px',
margin: '10px'
}}
>
{props.children}
</a>
);
}
function StyledJsxTest({ isLoggedIn, areButtonsVisible }) {
return (
<div>
<h1>This is a headline</h1>
<div>
<Button className="button" href="/dashboard">Test</Button>
{isLoggedIn ?
<Button className="button" href="/dashboard">Dashboard</Button>
:
<Button className="button" href="/signIn">Log In</Button>
}
</div>
</div>
)
}
export default StyledJsxTest
Upvotes: 0