0
votes

I am using a styled-component ternary operator on their template literal adaption based on props.

While I have a few CSS properties that are functioning accordingly to documentation, one such instance is malfunctioning, or so it seems.

export const InfoContainer = styled.div`
/* color: #fff; */
background: ${({lightBg}) => (lightBg ? 'tan' : 'purple')};

/* background: #fff999; */

@media screen and (max-width: 768px) {
    padding: 100px 0;
}
`

Here is my styled div containing a template literal with a ternary that 'adapts' based on true or false.

const TopLevelContainerObjExample = ({ lightBg }) => {
   return (
      <>
        <InfoContainer id={id} lightBg={lightBg}>
            <InfoWrapper>

A snipped of a react component implementing the styled div.

I am using an obj to deconstruct 'lightBg' into each instance of a component that uses the InfoContainer style. It works fine with other styled components that contain template ternaries, just not with this 'lightBg'.

Here is the dataObj first 3 lines:

export const homeObjOne = {
id: 'about',
lightbg: true,
lightText: true,

One important note: The lightBg property on the InfoContainer is undefined, as long as I pass in lightBg as 'lightBg={lightBg}' as below. Picture showing undefined

It does not do this for any other styled components, which is strange.

Another note, when I pass in a CSS color into lightBg property on the actual component I sometimes will change to that color. Other note: the background color will default to the false in the ternary statement.

Please help me to elaborate if you feel I left any information out. If you could help me refine the terminology for any aspect of my problem, I'd appreciate that, and lastly, if you could help me with what aspect of the styled-components/react is malfunctioning I'd be appreciative.

Thanks!

1
there is a typo. at your homeObjOne is lightbg instead of lightBgbuzatto
Wow, yes it is, maybe SO should create a section for typo checking. >.< Maybe there is a vscode extension that checks variables across files for grammar...Greg Iven
since you are passing a variable, you would need to use typescript for that or use PropTypes to declare the expected props reactjs.org/docs/typechecking-with-proptypes.htmlbuzatto

1 Answers

0
votes

You shouldn't add lightBg={lightBg} to InfoContainer, if you want lightBg simply add lightBg={true} or just LightBg, if you omit this props you will have purple background.

export const InfoContainer = styled.div`
/* color: #fff; */
background: ${lightBg => lightBg ? 'tan' : 'purple'};

/* background: #fff999; */
@media screen and (max-width: 768px) {
    padding: 100px 0;
}
`
export default function App() {
  return (
    <div className="App">
      <InfoContainer lightBg/>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}