DEV Community

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

Posted on • Originally published at maximeblanc.fr

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

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.

Top comments (3)

Collapse
 
exodu5 profile image
Clément Frémont

JS is awesome

Collapse
 
jeansmaug profile image
jean-smaug

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

Collapse
 
hughsato profile image
hugh sato

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...