Student
Student

Reputation: 15

change div background color on click REACT

The function "toggleselect" works as intended but I also need to change the background color of the division. Any ideas?

render: ({id}) => (
          <div id={id} className='button blue' onClick={()=>toggleSelect(id)}>
            <a>
              <div role="button">
                <label>Form: </label><input type='text'></input> <br></br>
        
                <label>Func: </label><input type='text'></input>
              </div>
            </a>
          </div>
        )

Upvotes: 0

Views: 2400

Answers (3)

Ktoxcon
Ktoxcon

Reputation: 434

Create a state with a different class name then pass it to the className attribute in your element, in your event handler use the setState function to change the class state to another class.

If you're using hooks:

const [clickedStyle, setClickedStyle] = React.useState('')//your default class;

//In your element
<div className={clickedStyle} >

//In your event handler
const handleClick = (_event) => {
  //OTHER LOGIC
  setClickedStyle('');//Your other class
}

If you're using class components:

//Your state
this.state = {
  clickedStyle: ''
}

//Your event handler
function handleClick(_event){
  //Other logic...
  this.setState({ clickedStyle: '' }) //Change your default class
}

//In your element
<div className={this.state.clickedStyle} >

Upvotes: 1

Someone Special
Someone Special

Reputation: 13588

Css works, but you also choose to do it more dynamically.

const toggleColor = () => {

   //assuming toggleSelect set state for `selected` state
   switch (selected){
       case 'blue': return 'blue'
       case 'red': return 'red' //or whatever #hexColor
       return: 'inherit'
   }

}


render: ({id}) => (
          <div id={id} 
               className='button blue' 
               style={{ color: toggleColor() }}
               onClick={()=>toggleSelect(id)}>
            <a>
              <div role="button">
                <label>Form: </label><input type='text'></input> <br></br>
        
                <label>Func: </label><input type='text'></input>
              </div>
            </a>
          </div>
        )

Upvotes: 0

Cole Henrich
Cole Henrich

Reputation: 165

.buttonblue:active {
  color: #0070f3; 
}

That is blue, by the way - the common blue that links look like. Play around, any hex or colorname works.

If you need a further explanation, that is CSS, and you are using the :active aspect of css, which allows you to set the behavior when something is clicked.

I'm considering removing this. It doesn't answer your question, I've realized.

Upvotes: 0

Related Questions