I am making a project on React and have come across an error which I have given below.
I am trying to resolve the error but am unable to do so.
Can someone please help?
The error is as follows:
Cannot read properties of undefined (reading ‘toLowerCase’)
TypeError: Cannot read properties of undefined (reading ‘toLowerCase’)
App.js
import "./App.css";
import Navbar from "./Components/Navbar";
import TextForm from "./TextForm";
import React, { useState } from "react";
import Alert from "./Components/Alert";
function App() {
const [mode, setMode] = useState("light");
const [alert, setAlert] = useState(null);
const showAlert = (message, type) => {
setAlert({
msg: message,
type: type,
});
setTimeout(() => {
showAlert(null);
}, 1000);
};
const toggleMode = () => {
if (mode === "light") {
setMode("dark");
document.body.style.backgroundColor = "black";
showAlert("The dark mode has been set", "success");
} else {
setMode("light");
document.body.style.backgroundColor = "white";
showAlert("The light mode has been set", "success");
}
};
return (
<>
<Navbar toggleMode={toggleMode} mode={mode} />
<Alert alert={alert} />
<TextForm
heading="This is textarea"
mode={mode}
alert={alert}
showAlert={showAlert}
/>
</>
);
}
export default App;
Alert.js
import React from "react";
export default function Alert(props) {
const capitalize = (word) => {
const lower = word.toLowerCase();
return lower.charAt(0).toUpperCase() + lower.slice(1);
};
return (
props.alert && (
<div
class={`alert alert-${props.alert.type} alert-dismissible fade show`}
role="alert"
>
<strong>{capitalize(props.alert.type)}</strong>:{props.alert.msg}
<button
type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"
></button>
</div>
)
);
}
3
Answers
TL;DR
What you might want is to
setAlert
instead of callingshowAlert
(which also causes an infinite loop) in thesetTimeout
function:When
showAlert(null)
is called, it resolves intosetAlert({ msg: null, type: undefined })
.The
alert
itself is not not empty:{ msg: null, type: undefined }
, which makesprops.alert
truthy, butprops.alert.type
isundefined
, socapitalize(props.alert.type)
receives anundefined
.Error cause is because the in the
capitalize
function you should check if word is not undefined or null then you should perform further operations, in your case operation is.toLowerCase()
With "showAlert(null)" call, the alert object is not technically empty as it has a "msg" property with a value of null, its "type" property is undefined.
That means props.alert is truthy, props.alert.type is undefined, hence you are getting this error.