How to change color of a div with button click on Reactjs + CSS

Asked

Viewed 1,471 times

0

I’m trying to change the color of div with button click, apparently it was supposed to work, but it only works on the second click, I don’t understand.

The code is like this :

The function I change the color:


  function Click( id: string,color: string) {
    let element = document.getElementById(id);
    if (element != null) {
      element.style.backgroundColor = active ? color : "#C4C4C4";
    }

  }

The party’s JSX specifies:

        <button
          className="button__carrosel"
          onClick={(event) => Click(id, acao, color)}
        >
          <div id={id} className="rectang">
            {title}
          </div>
        </button>

It works when I click twice, but I wanted it to change color on the first click. I used getElementById, but I tried changing the name of the class also when the button was active, but the same, only works in the second click. Does anyone have any notion of

2 answers

2


There are several strategies to change colors of some element with but, yours was not the best choice, because, is mixing commands, components in need to have global or local states for change, a basic example for changes in a div making toggle (true or false) and changing the color:

1 ) Naturally shaped React state

function App() {
  const [toogle, setToogle] = React.useState(true);
  const [cor, setCor] = React.useState('#c3c3c3');
  React.useEffect(() => {
    setCor((state) => toogle ? '#c3c3c3': '#446677');
  }, [toogle]);
  return (
    <div>
      <button
          onClick={e => 
            setToogle(state => !state)}
       >Alterar</button>
       <br /><br />
       <div style={{
          height: '200px', 
          width: '200px', 
          backgroundColor:cor,
        }}>      
       </div>
    </div>
  )
}

ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

where the state will control the two colors that were stipulated in that code.

2 ) Reference of the element:

By reference of div we can also change colors of any screen element, example:

function App() {
  const refDiv = React.useRef()  
  const [toogle, setToogle] = React.useState(true);  
  React.useEffect(() => {    
    if (refDiv.current) {
      refDiv.current.style.backgroundColor = '#c3c3c3';
      refDiv.current.style.height = '200px';
      refDiv.current.style.width = '200px'
    }
  }, []);
  React.useEffect(() => {    
    if (refDiv.current) {
      if (toogle) {
        refDiv.current.style.backgroundColor = '#c3c3c3';
      } else {
        refDiv.current.style.backgroundColor = '#446677';
      }
    }
  }, [toogle]);
  
  return (
    <div>
      <button
          onClick={e => 
            setToogle(state => !state)}
       >Alterar</button>
       <br /><br />
       <div ref={refDiv}>      
       </div>
    </div>
  )
}

ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

is an unusual way, particularly not user, but, this way found to access the <div> by reference, some events are even cool to use for example put focus() in elements <input />, then the first option is excellent and does not cause you future problems.

3 ) With Styled Components: website

This form is widely used to stylize components of dynamically by properties the element is changed:

const DivColor = window.styled.div`
  background: ${({toggle}) => toggle ? '#c3c3c3': '#446677'};
  height: 200px;
  width: 200px;
`;

function App() {
  const [toggle, setToggle] = React.useState(true);
  return (
    <div>
      <button
          onClick={e => 
            setToggle(state => !state)}
       >Alterar</button>
       <br /><br />
      <DivColor toggle={toggle}></DivColor>      
    </div>
  )
}

ReactDOM.render( <App/> , document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/react-is/umd/react-is.production.min.js"></script><script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root">Carregando ...</div>

The 3 forms work, the 1 and the 3 are the most recommended for working with state and commands of the React to 2 are more for events or something specific, but as said not much used for stylization.

0

Adding styles this way is not very interesting. I may suggest that you create a component for this button and have a state to control whether it is active or not as in the following example code:

const Button = ({ title }) => {
  const [active, setActive] = useState(false);

  return <button onClick={() => { setActive(true) }>
    <div className={`${active ? 'active' : ''}`}>{title}</div>
  </button>
}

This way, the moment you click the status change button will cause the elements of this component to be rendered again by changing the style of your div.

  • Entendiii! What if I had something like this: const [active, setActive] = useState({ card1: false, card2: false, card3: false, card4: false, card5: false, card6: false, card7: false, }); and I had <div classname={${active.id ? 'active' : ''}} id={id} > {title} </div> in which this "id" was card1 or card2 etc... it did not recognize id as card1 card2, as I could solve Iss?

  • Any doubt beyond your original question automatically generates a new question for you @Rindi! does this generate a new question with that comment and clear clarifies as much as possible

  • But I tried to do it and they said it was a duplicate question of this now, I didn’t understand

Browser other questions tagged

You are not signed in. Login or sign up in order to post.