Search code examples
reactjsstyled-components

How to add custom css with styled component and reactjs? Warning: Received false for a non-boolean attribute isfirstimageattachment


I like to add styles based on the props.

import   {ArrowBackIcon} from './styles';

const App = () => {
...

  const isFirstImageAttachment = (index) => {
    return (
      filteredImages.length &&
      filteredImages[0]?.uuid === attachments[index]?.uuid
    );
  };

...

  return (
    <div className="App">
     ...

      <ArrowBackIcon
        isfirstimageattachment={isFirstImageAttachment(idx)}
        onClick={clickBackAttachment}
      />

      ...
    </div>
  );
};

)

styles.js

export const ArrowForwardIcon = styled(ForwardArrowIcon)`
  ...
  display: ${props => (props.isfirstimageattachment ? 'none' : 'block')}; ;
`;

isFirstImageAttachment is supposed to return true or false so depending on that value I like to hide or show ArrowForwardIcon component.

I'm getting an error saying Warning: Received false for a non-boolean attribute isfirstimageattachment.If you want to write it to the DOM, pass a string instead: isfirstimageattachment="false" or isfirstimageattachment={value.toString()}

I don't want to do isfirstimageattachment="false" because isfirstimageattachment doesn't always return false. Also this function doesn't return string so isfirstimageattachment={value.toString()} don't work the way I want to.

Is there any I can do?

Attempts

What I figured out is even though I passed string false style didn't change.

  return (
    <div className="App">
     ...

      <ArrowBackIcon
        isfirstimageattachment="false"
        onClick={clickBackAttachment}
      />

      ...
    </div>

I saw the element got applied display: none; Is this not the way giving the props to styled component?


Solution

  • import   {ArrowBackIcon} from './styles';
    
    const App = () => {
    ...
    
      const isFirstImageAttachment = (index) => {
         const showEl = filteredImages.length &&
          filteredImages[0]?.uuid === attachments[index]?.uuid;
         return showEl ? 'hidden' : 'visible';
      };
    
    ...
    
      return (
        <div className="App">
         ...
    
          <ArrowBackIcon
            isfirstimageattachment={isFirstImageAttachment(idx)}
          />
    
          ...
        </div>
      );
    };
    
    )
    

    styles.js

    export const ArrowBackIcon = styled(BackArrowIcon)`
      visibility: ${props => props.isfirstimageattachment};
    `;
    

    I was able to add style dynamically this way!