Rendering Issue in React

Ive been going insane for the past hour trying to figure out his bug "Warning: Cannot update a component (App) while rendering a different component (Nav). To locate the bad setState() call inside Nav, follow the stack trace as described in https://reactjs.org/link/setstate-in-render"

import React, {useState, useEffect} from 'react'
import React, {useState, useEffect} from 'react'
import './App.css';
import Cart from './pages/cart'
import Home from './pages/home'
import Drawings from './pages/drawings'
import Paintings from './pages/paintings'
import Photos from './pages/photos'
import Nav from './pages/components/nav'



const App = ()=> {
const [page, setPage] = useState('home');

if(page=='home')
return(
  <>
  <Nav setPage={setPage}/>
  <Home/>
  </>
)
else if(page=='drawings')
  return(
    <>
    <Nav setPage={setPage}/>
    <Drawings/>
    </>
  )

}

export default App;

Nav.js

import React from 'react'
import 'C:/Users/Bharat/Desktop/ecommerce/vgogh/src/App.css'
const Nav = ({setPage}) => {
    return (
        <>
            <nav className='navBar'>
            <div className="home"><button onClick={setPage('home')}>Home</button></div>
                <ul>
                    <li className="navItems"><button onClick={()=>setPage('paintings')}>Painting</button></li>
                    <li className="navItems"><button onClick={()=>setPage('photos')}>Photos</button></li>
                    <li className="navItems"><button onClick={()=>setPage('drawings')}>Drawings</button></li>
                    <li className="navItems" id='cart'><button onClick={()=>setPage('cart')}>Cart</button></li>
                </ul>
            </nav>
        </>
    )
}
export default Nav

>Solution :

In Nav.js

Instead of writing this:

<button onClick={setPage('home')}>Home</button>

You can write :

<button onClick={()=>setPage('home')}>Home</button>

I think you got it.
To know more about handling event you can read their documentation. https://reactjs.org/docs/handling-events.html

Leave a Reply