skip to Main Content

Gettting waring in following code i want to display meassage ,but neither it is showing nor dissmiss the button

function App(){
  const [mode,setMode]=useState('light');
//getting warning for below line
  const [alert,setAlert]=useState(null);

  const showAlert=(message,type)=>{
    setAlert(
    {msg : message,
    type : type
    })
  };

  const toggleMode=()=>{
    if(mode==='light'){
      setMode('dark');
      document.body.style.backgroundColor='#56595b'
      showAlert("Enable dark mode","success");
    }
    else{
      setMode('light');
      document.body.style.backgroundColor='white'
      showAlert("enable light mode","success")
    }
  }


  return(
    <Navbar title="Blog"  mode={mode} toggleMode={toggleMode}/>
    <Alert alert="wtf"/>
    </>
  );
}

export default App;    

//Below is Alert Component

import React from 'react'

export default function Alert(props) {
  return (
    <>
     props.alert  && <div className="alert alert-warning alert- 
     dismissible fade show" role="alert">
     <strong>{props.alert.type}</strong> : {props.alert.msg}
     <button type="button" className="close" data-dismiss="alert" aria- 
     label="Close">
     <span aria-hidden="true">&times;</span>
         </button>
      </div>
    </>
  )
}

WARNING in [eslint] I want to display alert message on screen. but it is not showing

2

Answers


  1. Maybe this:

    <Alert alert="wtf"/>

    Should be:

    <Alert alert={alert}/>

    That should fix the lint warning.

    For that null check to work you need to remove that fragment <></>, or place it between {}. In my opinion it’s cleaner to just remove the fragment:

    export default function Alert(props) {
      return (
        props.alert && (
          <div
            className="alert alert-warning alert-dismissible fade show"
            role="alert"
          >
            <strong>{props.alert.type}</strong> : {props.alert.msg}
            <button
              type="button"
              className="close"
              data-dismiss="alert"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
        )
      )
    }
    

    As someone mentioned, "alert" is not a good variable name. There’s a list of keywords that can’t be used , alert is not on the list but there’s window.alert, which can cause confusion later. Also may be a good idea to initialize your state with an empty object instead of null it’s often considered a good practice. Like this for example:

    const [alertMessage, setAlertMessage] = useState({msg:"",type:""})
    

    This allows you to get better performance by removing the null check on your component like so:

    export default function Alert(props: any) {
      return (
        <div
          className="alert alert-warning alert- dismissible fade show"
          role="alert"
        >
          <strong>{props.alert.type}</strong> : {props.alert.msg}
          <button
            type="button"
            className="close"
            data-dismiss="alert"
            aria-label="Close"
          >
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      )
    }
    

    Hope it helps

    Login or Signup to reply.
  2. You have a few issues.

    1. You are using Boostrap modal, but only a small piece of it
    2. Closing the dialog requires you to set the alertObj to null
    3. You need to use the function version for setting the mode state

    Also, avoid simple variables names like alert, string, window, because these are typically reserved works for JavaScript. Make your variable more descriptive i.e. dialogData or something to that effect.

    See the working snippet below:

    const { useCallback, useState } = React;
    
    const Navbar = ({ mode, title, toggleMode }) => {
      return (
        <header>
          <h1>{title}</h1>
          <nav>
            <ul>
              <li><a href="#home">Home</a></li>
              <li><a href="#contact">Contact</a></li>
              <li><a href="#about">About</a></li>
            </ul>
          </nav>
          <div>
            <button onClick={toggleMode}>Toggle Theme</button>
          </div>
        </header>
      );
    };
    
    const Alert = ({ alertObj, closeAlert }) =>
      alertObj != null && (
        <div className="alert alert-warning alert-dismissible fade show" role="alert">
          <strong>{alertObj.type}</strong>: {alertObj.msg}
          <button type="button" className="close" data-dismiss="alert" aria-label="Close"
              onClick={closeAlert}>
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      );
    
    const App = () => {
      const [mode, setMode] = useState('light');
      const [alertObj, setAlertObj] = useState(null);
    
      const showAlert = useCallback((message, type) => {
        setAlertObj({ msg : message, type : type })
      }, []);
    
      const closeAlert = useCallback((message, type) => {
        setAlertObj(null);
      }, []);
    
      const toggleMode = useCallback(() => {
        setMode(currentMode => {
          if (currentMode === 'light') {
            document.body.style.backgroundColor = '#56595b';
            showAlert("Enabled dark mode", "success");
            return 'dark';
          } else {
            document.body.style.backgroundColor = 'white';
            showAlert("Enabled light mode", "success");
            return 'light';
          }
        });
      }, []);
    
      return (
        <React.Fragment>
          <Navbar title="Blog" mode={mode} toggleMode={toggleMode} />
          <Alert alertObj={alertObj} closeAlert={closeAlert} />
        </React.Fragment>
      );
    };
    
    ReactDOM
      .createRoot(document.getElementById("root"))
      .render(<App />);
    header { display: flex; flex-direction: column; justify-content: center; align-items: center; }
    header nav ul { display: flex; margin: 0; padding: 0; gap: 1rem; justify-content: center; }
    header nav ul li { display: flex; margin: 0; padding: 0.5rem; border: thin solid grey; }
    header div button { margin-top: 1rem; }
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS" crossorigin="anonymous"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search