M.Abdullah
M.Abdullah

Reputation: 87

Having problem in changing css using useState in react

I'm trying to build a modal in react. When it's opened, the background or the body color must change to a darker one and the modal should open, when closed, everything must go back to normal. I tried to achieve this by this method:

const [modalState, setModalState] = useState(false);
const [modalBg, setModalbg] = useState(false);

function handleClick() {
    setModalState(true);
    setModalbg(true);
    
}
return (
  {
      !modalState ?
       null
       : <Modal modalState = {setModalState}/>
  }
  {
      !modalBg ?
       document.body.style.backgoundColor = "ffff"
      : document.body.style.backgoundColor = 'rgba(39, 38, 38, 0.616)'
  }
  <button onClick= {handleClick}>Open</button>
  
)

The problem is, that instead of changing color of the body, it just renders text to the page like '#fff' or 'red'. I don't know why that happens, can anyone help?

Thanks!

Upvotes: 0

Views: 1727

Answers (2)

Ibrahim Farooq
Ibrahim Farooq

Reputation: 438

Your way isn't really the "React" way of handling modals. First of all, I can't stress enough the use of portals when creating modals. Do look this up to really understand what portals are and how they help you.
Moving on, you can create a modal component as shown below and trigger this component however you want, using a state. Just make sure to pass the setter of that state to the component as a prop, in my case setShowModal.
Your modal's background is contained in the div my-modal-container and you can change that however you wish.

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

const MyModal = ({setShowModal}) => {

    const handleClose = () => {
        setShowModal(false)
    };

    return ReactDOM.createPortal(
        <div className='my-modal-container'>
            <div class='my-modal-body'>
                //Place all you modal body here
            </div>
        </div>,
        document.getElementById('portal')
    );
};
export default MyModal;

If you choose to you use portals as above, make sure you add <div id="portal"></div> in your index.html file right below <div id="root"></div>.

Upvotes: 2

S. Singh
S. Singh

Reputation: 99

You should not set the background colour of the body in the return function. That is meant to return the JSX.

Try using a useEffect hook something like:

useEffect(() => {
  if (modalBg) {
    document.body.style.backgoundColor = "rgba(39, 38, 38, 0.616)";
  } else {
    document.body.style.backgoundColor = "ffff";
  }
}, [modalBg]);

Upvotes: 0

Related Questions