i'm creating form component to use the form in 2 different page and i want to check if is value is defind set it or give it a empty string ,but it doesn't work whem short circuit being used or ternary operator
here is my code :
import { useNavigate } from "react-router-dom";
import classes from "./EventForm.module.css";
function EventForm({ method, event }) {
const navigate = useNavigate();
function cancelHandler() {
navigate("..");
}
return (
<form className={classes.form}>
<p>
<label htmlFor="title">Title</label>
<input
id="title"
type="text"
name="title"
required
defaultValue={event.title || ""} // this line
/>
</p>
<p>
<label htmlFor="image">Image</label>
<input
id="image"
type="url"
name="image"
required
defaultValue={event.image || ""}
/>
</p>
<p>
<label htmlFor="date">Date</label>
<input
id="date"
type="date"
name="date"
required
defaultValue={event.date || ""}
/>
</p>
<p>
<label htmlFor="description">Description</label>
<textarea
id="description"
name="description"
rows="5"
required
defaultValue={event.description || ""}
/>
</p>
<div className={classes.actions}>
<button type="button" onClick={cancelHandler}>
Cancel
</button>
<button>Save</button>
</div>
</form>
);
}
export default EventForm;
and i'm getting this error : Cannot read properties of undefined (reading 'title') while it should be fixed
i tried ternary operator and short circuiting but it only lead to failiure
It was thrown error because your
eventmight isnullorundefinedThe error said:
Cannot read properties of undefined (reading 'title')-> It meansundefined.titlecrash hereThere are many ways to fix it.
eventbefore callingevent = {}event?.titlehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining