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">×</span>
</button>
</div>
</>
)
}
WARNING in [eslint] I want to display alert message on screen. but it is not showing
2
Answers
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:
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:This allows you to get better performance by removing the null check on your component like so:
Hope it helps
You have a few issues.
alertObj
tonull
mode
stateAlso, 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: