Search code examples
reactjsstylesjsxstyled-components

Styled-JSX variables not working


I have installed styled-jsx using [email protected] and am doing something like so:

import React, { Component } from 'react'

export default Index class extends Component {
  constructor(props){
   super(props)
   this.state = { clicked: false}
  }
  render(){
   return(){
    <div>
    <button onClick={() => this.setState({clicked: !this.state.clicked}}}>Hello</button>
    <style jsx>{`
    button {
     background-color: ${this.state.clicked ? 'red' : 'blue'}
    }
    `}<style>
  }
 }
}

No styles what so ever are being applied and I console logged out the clicked state and it is being changed.


Solution

  • Here's working example. You had lot of typo's in there. I assume you are not using appropriate IDE that usually points out at all those issues.

    Here's the working code: https://stackblitz.com/edit/react-3ttfch

    Here's your fixed typoless code:

    class Index extends Component {
      constructor(props) {
        super(props)
        this.state = { clicked: false }
      }
      render() {
        return (
          <div>
            <button onClick={() => this.setState({ clicked: !this.state.clicked })}>
              Hello
            </button>
            <style jsx>{`
              button {
                background-color: ${this.state.clicked ? 'red' : 'blue'}
              }
            `}</style>
          </div>
        );
      }
    }