Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading