Home > Mobile >  Rendering Issue in React
Rendering Issue in React

Time:06-13

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

CodePudding user response:

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

CodePudding user response:

After some scouring, I figured out I missed an arrow function in my "home" button in nav.js which as plichard pointed out caused an infinite loop.

Previous <div className="home"><button onClick={setPage('home')}>Home</button></div>

Solved <div className="home"><button onClick={()=>setPage('home')}>Home</button></div>

  • Related