I am studying styled-component, and I faced some problems in 'adapting based on props' part.
import './App.css';
import styled from 'styled-components'
const PrimaryButton = styled.button`
color: ${props=>props.primary?"white":"black"};
background-color: ${props=>props.primary?"blue":"gray"};
`;
function App() {
return (
<div>
<PrimaryButton>Normal</PrimaryButton>
<PrimaryButton primary>Primary</PrimaryButton>
</div>
);
}
export default App;
At first, I tried with this code, and the console told me to use primary=true, so I did.
But there was a following error in the console which says 'it looks like an unknown prop "primary" is being sent through to the DOM'. To solve this problem, I briefly scanned the styled-components document. I found out that they use $primary instead of primary. So the final code looks like this:
import './App.css';
import styled from 'styled-components'
const PrimaryButton = styled.button`
color: ${props=>props.$primary?"white":"black"};
background-color: ${props=>props.$primary?"blue":"gray"};
`;
function App() {
return (
<div>
<PrimaryButton>Normal</PrimaryButton>
<PrimaryButton $primary>Primary</PrimaryButton>
</div>
);
}
export default App;
I could no longer see the errors, but still I don't know the reason it happened and is solved.
What does $ mean?
These are used by styled-components and they have nothing to do with React.
If you want to prevent props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.
you can learn more here you can find an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With