I have this react code
const MenuItem = ({title, imageUrl, linkUrl}) => {
const [isClicked, setIsClicked] = useState(false);
const handleClick = () =>{
setIsClicked(true);
}
const handleLocation = () => {
if(window.location.pathname === '/movie'){
<MoviePage categoryId={linkUrl}/>
}
}
return (
<div className="menu-item">
<div className="image-container" style={{backgroundImage:`url(${imageUrl})`}}/>
<div className="image-content"
onClick={handleClick}>
{isClicked ? {handleLocation}: null}
<h1>{title}</h1>
</div>
</div>
);
}
Here, on the onclick event I want to render the component on another page, so I used window.location, but getting this error
Uncaught Error: Objects are not valid as a React child (found: object with keys {handleLocation}). If you meant to render a collection of children, use an array instead.
This is not how you would navigate in a React app - you need a routing solution, for example https://reactrouter.com/
With react-router you can define and configure your routes and navigate to them without reloading the page.
Try to work you through the tutorial: https://reactrouter.com/docs/en/v6/getting-started/tutorial
Basically, you would have a router with routes like this:
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="expenses" element={<Expenses />} />
<Route path="invoices" element={<Invoices />} />
</Routes>
</BrowserRouter>
From offical document,
You can put any valid JavaScript expression inside the curly braces in JSX.
JSX is an Expression Too After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.
<div
className="image-content"
onClick={handleClick}
>
{isClicked ? {handleLocation} : null} // should be {isClicked ? handleLocation() : null}
<h1>{title}</h1>
</div>
In your code, handleLocation with curly braces will be the Javascript expression by JSX grammer. So {handleLocation} will be a reference of your function handleLocation. It is never called. You should make it called like handleLocation().
const handleLocation = () => {
if (window.location.pathname === '/movie') {
<MoviePage categoryId={linkUrl}/> // it is just a expression, not returns any value
}
}
One more change you need in your code is to return JSX element in handleLocation. <MoviePage /> in the if statement is just a expression. So this function whill never return any value. You should add return in front of <MoviePage />, then ReactDOM will render this component.
return <MoviePage categoryId={linkUrl} />