If you use styled-components
, you maybe encountered the following error.
Warning: Received "true" for a non-boolean attribute
There is an official solution that you can find here. I'll present an alternative to this solution.
The trick is to use the unary plus operator to convert boolean to number.
// Convert boolean to numbers
+true; // 1
+false; // 0
// Conditions are still valid using 0 and 1
0 ? "jean" : "smaug"; // smaug
1 ? "jean" : "smaug"; // jean
In order to make a real world example, we'll style the Link
component from react-router
.
import styled from "styled-components";
import { Link } from "react-router";
const StyledLink = styled(Link)`
color: ${({ inverted }) => (inverted ? "white" : "chartreuse")};
`;
function Navbar() {
return (
<nav>
{# Bad #}
<StyledLink inverted={true}>Home</StyledLink>
{# Good #}
<StyledLink inverted={+true}>About</StyledLink>
</nav>
);
}
Fixing this error is very simple. You just need to add +
before your booleans values. According to MDN unary operator is the preferred way for number conversion.
You can find the banner image here.
Thanks for reading.
Top comments (3)
JS is awesome
Cimer, c'est ça de pris en référencement
Adding comment here to address anyone dealing with this issue in 2022, there's a "transient props" thing you can now use in styled-components that prevent props from being passed all the way to the DOM.
styled-components.com/docs/api#tra...