Search code examples
reactjsreact-hooksstyled-components

Can't figure out how change css using props in styled components and a useState hook


Trying to change the grid-column value of a styled.div based on user input via styled buttons. I have the grid-column values set up as props in a styled component, like so:

const Highlight = styled.div`
  display: block;
  margin: -0.5rem;
  padding: 0;
  border: 1px solid #00fff3;
  border-radius: 16px;
  z-index: 2;
  background: hsla(177, 100%, 21%, 0.25);
  grid-row: 1 / 2;
  grid-column:
    ${props =>
        props.key === 'C' ? `1 / 9` :
        props.key === 'Db' ? `2 / 10` :
        props.key === 'Eb' ? `3 / 11` : 
        `1 / 9`
     };
`

and the value of the prop is in state, like so:

const [ key, setKey ] = useState()

...then the prop is on the styled component, like so:

<Highlight key={key}/>

...then the value of that prop is changed when any of the following buttons is pressed:

<C onClick={() => setKey('C')}>C</C>
<D onClick={() => setKey('D')}>D</D>
<E onClick={() => setKey('E')}>E</E>
<F onClick={() => setKey('F')}>F</F>
<G onClick={() => setKey('G')}>G</G>
<A onClick={() => setKey('A')}>A</A>
<B onClick={() => setKey('B')}>B</B>
<DFlat onClick={() => setKey('Db')}>Db</DFlat>
<EFlat onClick={() => setKey('Eb')}>Eb</EFlat>
<GFlat onClick={() => setKey('Gb')}>F#/Gb</GFlat>
<AFlat onClick={() => setKey('Ab')}>Ab</AFlat>
<BFlat onClick={() => setKey('Bb')}>Bb</BFlat>

...but it does not work yet, so I'm not doing something right, or I am missing something, but I do not know what I'm doing wrong.


Solution

  • key is an implicit prop in ReactJS. From the docs:

    Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name

    List and Keys - Docs

    So to pass the prop, you need to use a different name from key and you should be good to go.