Al_Milligan
Al_Milligan

Reputation: 119

how to change component background color changing state in react.js?

I am working on a task where I need to change component background by clicking on a button and changing state. I am not supposed to use React Hooks. So far I've got:

import React from 'react'
import ReactDOM from 'react-dom'

class Main extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    const {
      colorChange,
      styles
    } = this.props

    const text = this.props.data
    return (
      <main style={styles}  >
        <h1>welcome</h1>
        <button
          onClick={colorChange}
        >
Change color
        </button>
   
      </main>
    )
  }
}

class App extends React.Component {
  state = {
    styles: { backgroundColor: 'white' },
  }

  colorChange = () => {
    let backgroundColor = 'white'
    let changedColor = 'black'
    let backGround = this.state.styles==='white' ? changedColor : backgroundColor
  this.setState({backGround})}
  render() {

    return (
      <Main      
        colorChange={this.colorChange}
      
      />
    )
  }
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

but that doesn't do anything. Where am I making a mistake?

Upvotes: 2

Views: 5934

Answers (2)

Gabriel Nadaleti
Gabriel Nadaleti

Reputation: 1646

First pass styles as a prop to main <Main colorChange={this.colorChange} style={this.state.styles} /> its currently undefined.

second, this.state.styles is as object and you're comparing like

this.state.styles === "white"

and you should acess backgroundColor in the object:

this.state.styles.backgroundColor === "white"

and last when you do setState({backGround}) you're creating a item with key backGround (which isn't a valid css property) and isn't inside styles tag as well. Your state end up being like this:

this.state = {
   backGround: 'black',
   styles: {
     backgroundColor: 'white'
   }
}

so do like this:

this.setState({
  styles: {
     backgroundColor: backColor
  }
})

also i recomend calling colorChange like this to avoid infinite re-renders:

<button onClick={() => colorChange()}>Your Button</button>

Upvotes: 2

helrabelo
helrabelo

Reputation: 551

My suggestion would be that you simply use the onColorChange() function to add/remove a class.

If you MUST pass the styles as a parameter, you could also save only the value of the color ('white', 'black') on the state and when you pass it on to the component use the value only

Upvotes: 1

Related Questions