DEV Community

loading...
Cover image for How to fix the 'Received "true" for a non-boolean attribute' error

How to fix the 'Received "true" for a non-boolean attribute' error

jeansmaug profile image jean-smaug Originally published at maximeblanc.fr ・1 min read

If you use styled-components, you maybe encountered the following error.

Warning: Received "true" for a non-boolean attribute
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

pic
Editor guide
Collapse
exodu5 profile image
Clément Frémont

JS is awesome

Collapse
jeansmaug profile image
jean-smaug Author

Cimer, c'est ça de pris en référencement