Bad setState call inside offcanvas component - reactjs

I'm getting a bad setState() error inside the sidebar bootstrap offcanvas component. It says it can't update the component App() while rendering a different component sidebar() Sorry but I had to delete a large section of my code which was a fetch call. Thanks.
Error: index.js:1 Warning: Cannot update a component (App) while rendering a different component (Sidebar). To locate the bad setState() call inside Sidebar, follow the stack trace as described in
App.js
import React, {useEffect, useState} from 'react';
import './App.css';
import MovieTag from "./components/MovieTag/MovieTag";
import Sidebar from "./components/MovieTag/Sidebar";
interface Movie {
id: number,
poster_path: string,
title: number
}
function App() {
const [movies, setMovies] = useState([]);
const [genre, setGenre] = useState(0);
const [sort, setSort] = useState("popularity.desc");
const [page, setPage] = useState(1);
function GetMovies(genreId: number, sortBy: string, page: number){
setGenre(genreId);
setSort(sortBy);
setPage(page);
return (
<div className={'container'}>
<Sidebar filterByGenre={(genre: number) => {
setGenre(genre);
}}
sortBy={(sort: string) => {
setSort(sort);
}}
pageFilter={(page: number) => {
setPage(page);
}}
/>
<div className={'row'}>
{movies.map((movie: Movie) => {
return (
<MovieTag key={movie.id}
poster={movie.poster_path}
title={movie.title}
/>
)
})}
</div>
</div>
);
}
export default App;
Sidebar.js
function Sidebar(props: any) {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<React.Fragment>
<Button variant={'secondary'} onClick={handleShow}>Filter</Button>
<Offcanvas show={show} onHide={handleClose}>
<Offcanvas.Header>
<Offcanvas.Title>Filter</Offcanvas.Title>
</Offcanvas.Header>
<Offcanvas.Body>
<DropdownButton title={'Genre'} drop={'end'}>
<Dropdown.Item eventKey={1}><button onClick={props.filterByGenre(28)}>Action</button></Dropdown.Item>
</DropdownButton>
</Offcanvas.Body>
</Offcanvas>
</React.Fragment>
)
}

The problem is on Sidebar component which is calling a setState of its parent component while rendering on <Dropdown.Item eventKey={1}><button onClick={props.filterByGenre(28)}>Action</button></Dropdown.Item>
If you need to call the function onClick, then create an arrow function to it.
onClick={() => props.filterByGenre(28)}

Related

useRef() returning 'undefined' when used with custom hook on initial render when using filter()

I have an image slider component and a simple custom hook that gets the refElement and the width of the element using the useRef hook. -
The code sandbox is here Image Slider
When I use the slider component and just map the data in without filtering, everything works fine. If I filter and map the data then I get Uncaught TypeError: elementRef.current is undefined . (In the sandbox you have to comment out the second instance (unfiltered) of SliderTwo to recreate the error. Why does it work without the filter but not with (when rendered by itself)? More in depth explanation below.
useSizeElement()
import { useState, useRef, useEffect } from 'react';
const useSizeElement = () => {
const [width, setWidth] = useState(0);
const elementRef = useRef();
useEffect(() => {
setWidth(elementRef.current.clientWidth); // This will give us the width of the element
}, [elementRef.current]);
return { width, elementRef };
};
export default useSizeElement;
I call the hook (useSizeElement) inside of a context because I need the width to use in another hook in a different component thus:
context
import React, { createContext, useState, useEffect} from 'react';
import useSizeElement from '../components/flix-slider/useSizeElement';
export const SliderContext = createContext();
export const SliderProvider = ({children}) => {
const { width, elementRef } = useSizeElement();
const [currentSlide, setCurrentSlide] = useState();
const [isOpen, setIsOpen] = useState(false)
console.log('context - width', width, 'elementRef', elementRef)
const showDetailsHandler = movie => {
setCurrentSlide(movie);
setIsOpen(true)
};
const closeDetailsHandler = () => {
setCurrentSlide(null);
setIsOpen(false)
};
const value = {
onShowDetails: showDetailsHandler,
onHideDetails: closeDetailsHandler,
elementRef,
currentSlide,
width,
isOpen
};
return <SliderContext.Provider value={value}>{children}</SliderContext.Provider>
}
I get the width of the component from the elementRef that was passed from the context.-
Item Component
import React, { Fragment, useContext } from 'react';
import { SliderContext } from '../../store/SliderContext.context';
import ShowDetailsButton from './ShowDetailsButton';
import Mark from './Mark';
import { ItemContainer } from './item.styles';
const Item = ({ show }) => {
const { onShowDetails, currentSlide, isOpen, elementRef } =
useContext(SliderContext);
const isActive = currentSlide && currentSlide.id === show.id;
return (
<Fragment>
<ItemContainer
className={isOpen ? 'open' : null}
ref={elementRef}
isActive={isActive}
isOpen={isOpen}
>
<img
src={show.thumbnail.regular.medium}
alt={`Show title: ${show.title}`}
/>
<ShowDetailsButton onClick={() => onShowDetails(show)} />
</ItemContainer>
</Fragment>
);
};
export default Item;
The width is passed using context where another hook is called in the Slider Component:
Slide Component
import useSizeElement from './useSizeElement';
import { OuterContainer } from './SliderTwo.styles';
const SliderTwo = ({ children }) => {
const {currentSlide, onHideDetails, isOpen, width, elementRef } = useContext(SliderContext);
const { handlePrev, handleNext, slideProps, containerRef, hasNext, hasPrev } =
useSliding( width, React.Children.count(children));
return (
<Fragment>
<SliderWrapper>
<OuterContainer isOpen={isOpen}>
<div ref={containerRef} {...slideProps}>
{children}
</div>
</OuterContainer>
{hasPrev && <SlideButton showLeft={hasPrev} onClick={handlePrev} type="prev" />}
{hasNext && <SlideButton showRight={hasNext} onClick={handleNext} type="next" />}
</SliderWrapper>
{currentSlide && <Content show={currentSlide} onClose={onHideDetails} />}
</Fragment>
);
};
export default SliderTwo;
Now everything works fine if I just map the data with no filters into the slider as shown in the sandbox. But if I apply a filter to display only what I want I get -
Uncaught TypeError: elementRef.current is undefined
I do know that you can't create a ref on an element that does not yet exist and I've seen examples where you can use useEffect to get around it but I can't find the solution to get it to work.
Here is the App.js - To see the error I'm getting, comment out the second instance of . As long as I'm running one instance without filtering the data, it works, but it won't work by itself.
import { useState, useEffect, Fragment } from "react";
import SliderTwo from "./components/SliderTwo";
import Item from "./components/Item";
import shows from "./data.json";
import "./App.css";
function App() {
const [data, setData] = useState(null);
const datafunc = () => {
let filteredData = shows.filter((show) => {
if (show.isTrending === true) {
return show;
}
});
setData(filteredData);
};
useEffect(() => {
datafunc();
}, []);
console.log("Trending movies", data);
return (
<Fragment>
<div className="testDiv">
{shows && data && (
<SliderTwo>
{data && data.map((show) => <Item show={show} key={show.id} />)}
</SliderTwo>
)}
</div>
<div className="testDiv">
<SliderTwo>
{shows.map((show) => (
<Item show={show} key={show.id} />
))}
</SliderTwo>
</div>
</Fragment>
);
}
export default App;
Full code: Sandbox - https://codesandbox.io/s/twilight-sound-xqglgk
I think it may be an issue when the useSizeElement is first mounted as the useEffect will run once at the beginning of each render.
When it runs at the first instance and the ref is not yet defined so it was returning the error: Cannot read properties of undefined (reading 'clientWidth')
If you modify your code to this I believe it should work:
import { useState, useRef, useEffect } from "react";
const useSizeElement = () => {
const [width, setWidth] = useState(0);
const elementRef = useRef();
useEffect(() => {
if (elementRef.current) setWidth(elementRef.current.clientWidth); //
This will give us the width of the element
}, [elementRef]);
return { width, elementRef };
};
export default useSizeElement;
This way you are checking if the elementRef is defined first before setting the width
UPDATE:
<Fragment>
<div className="testDiv">
<SliderTwo>
{shows
.filter((show) => {
if (show.isTrending === true) {
return show;
}
return false;
})
.map((show) => (
<Item show={show} key={show.id} />
))}
</SliderTwo>
</div>
{/* <div className="testDiv">
<SliderTwo>
{shows.map((show) => (
<Item show={show} key={show.id} />
))}
</SliderTwo>
</div> */}
</Fragment>

Destructed props sent to child component returning undefined

I'm a bit lost here. I've done this a bunch of time and have never had this issue before. I'm passing a boolean state to a modal component. I followed the code from the parent and it is set properly but as soon as it gets to the modal it returns as undefined.
Here is the parent:
import React, { useEffect, Fragment, useState } from 'react'
import './styles.css'
import LandingPageModal from './LandingPageModal'
import { testImages } from './testData'
const LandingPage = () => {
const [images, setImages] = useState([])
const [renderImages, setRenderImages] = useState(false)
const [showModal, setShowModal] = useState(false)
const [isLoaded, setIsLoaded] = useState(false)
useEffect(() => {
setImages(testImages)
setShowModal(true)
setIsLoaded(true)
}, [])
useEffect(() => {
if (images && images.length > 0) {
setRenderImages(true)
}
}, [images])
const FeaturedUsers = () => {
return (
renderImages ?
<Fragment>
<div className='grid'>
{images.map((image) => (
<img src={`/images/${image.src}`} alt={image.caption} />
))}
</div>
</Fragment> : ''
)
}
return(
isLoaded ?
<Fragment>
<FeaturedUsers />
<LandingPageModal show={showModal} />
</Fragment> : ''
)
}
export default LandingPage
and here is the modal:
import React, { useState, useEffect } from 'react'
import ReactModal from 'react-modal'
import './styles.css'
const LandingPageModal = ({ showModal }) => {
const [isModalOpen, setIsModalOpen] = useState(showModal)
console.log('Is Show: ' + showModal)
return (
<ReactModal
isOpen={isModalOpen}
>
<div className='main-wrapper'>
<div className='text'>
<p>
<strong>Welcome</strong>
<br />
<br />
Please sign in or sign up
</p>
</div>
</div>
</ReactModal>
)
}
export default LandingPageModal
In the LandingPage component, you accidentally renamed showModal to show.

How to render react component after function call?

My goal show custom antd modal after function (showCustomModal) call (like Modals.confirm).
CustomModal.tsx:
export function showCustomModal() {
return <Modal>custom modal</Modal>
}
Component.tsx
import { showCustomModal } from 'CustomModal'
const Component= () => {
const showModal = () => {
showCustomModal()
}
return <button onClick={showModal}>show modal</button>
}
React component at the end will need get called in return, here what you want do is use state to control when to show the component.
import { showCustomModal } from 'CustomModal'
const Component= () => {
const [show, setShow] = useState(false);
return (
<>
<button onClick={setShow(true)}>show modal</button>
{show && <showCustomModal />}
</>
)
}

How to change style property in react hooks on function call

On function call i was changing the image style using useState hooks
I was sending these property as an props
basically i want to a function which should contain style property for img and pass it to another component as propsstyle = {{opacity: ".3"}}
import React, { useState } from 'react';
import BackgroundImage from '../Image/Homepage/background.png'
const HomePage = () => {
const [modalShow, setModalShow] = useState(false);
const [image, setImage] = useState(BackgroundImage)
return (
<div>
<img src={image} className="first-image" alt="backGroundImage" />
</div>
<Modals
show={modalShow}
onhide={() => setModalShow(false)}
sendImages = {() => setImage( style = {{opacity: ".3"}} )}
/>
)}
this is throwing an error
sendImages = {() => setImage( style = {{opacity: ".3"}} )}
I think this not right approach
It looks like you want to make opacity dynamic, instead you manipulate image src...
import React, { useState } from 'react';
import BackgroundImage from '../Image/Homepage/background.png'
const HomePage = () => {
const [modalShow, setModalShow] = useState(false);
const [image, setImage] = useState(BackgroundImage);
const [opacity, setOpacity] = useState(1);
return (
<>
<div>
<img src={image} className="first-image" style={{opacity}} alt="backGroundImage" />
</div>
<Modals
show={modalShow}
onhide={() => setModalShow(false)}
sendImages = {() => setOpacity(0.3)}
/>
</>
)}
If you only wish to update the style property on function call, you must store the style property in state and not the image. Also the syntax for setImage is incorrect in your code
import React, { useState } from 'react';
import BackgroundImage from '../Image/Homepage/background.png'
const HomePage = () => {
const [modalShow, setModalShow] = useState(false);
const [imageStyle, setImageStyle] = useState({})
return (
<>
<div>
<img src={BackgroundImage} style={imageStyle} className="first-image" alt="backGroundImage" />
</div>
<Modals
show={modalShow}
onhide={() => setModalShow(false)}
sendImages = {() => setImageStyle({opacity: ".3"})}
/>
</>
)}
NOTE: Also please note that state updaters with hooks do not merge the values but override it. So if you wish to update only certain properties make use of state updater callback method to return the merged values yourself

Using React.memo and useCallback to prevent functions from causing re-renders

I am following this tutorial demonstrating react's 'useCallback' hook along with React.memo to prevent a function being render unnecessarily. To prove the concept we use useRef to console the number of renders. This worked with the function alone but i added a function to randomize the button background color and I can't seem to no prevent the rendering of both functions.
import React,{useState, useCallback, useRef} from 'react';
import './App.css';
const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`
const Button = React.memo(({increment, bgColor}) => {
const count = useRef(0)
console.log(count.current++)
return(
<button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
)
})
const App = React.memo(() => {
const [count, setCount] = useState(0)
const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)
const increment = useCallback(() => {
setCount(previousCount => previousCount + 1)
setColor(randomColor)
},[setCount,setColor])
return (
<div className="App">
<header className="App-header">
<h2>{count}</h2>
<Button increment={increment} bgColor={color}>increment</Button>
</header>
</div>
);
})
export default App;
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import React,{useState, useCallback, useRef} from 'react';
import './App.css';
const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`
const Button = React.memo(({increment, bgColor}) => {
const count = useRef(0)
console.log(count.current++)
return(
<button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
)
})
const App = React.memo(() => {
const [count, setCount] = useState(0)
const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)
const increment = useCallback(() => {
setCount(previousCount => previousCount + 1)
setColor(randomColor)
},[setCount,setColor])
return (
<div className="App">
<header className="App-header">
<h2>{count}</h2>
<Button increment={increment} bgColor={color}>increment</Button>
</header>
</div>
);
})
export default App;
It the example in the video you mentioned, the Button component does not change, because the props stay the same all the time. In your example, the increment stays the same, but the problem is that the bgColor changes with each click.
That means, that if you rendered only the main component and not the Button component, the background would have to be the same, but because it receives different background color each time, it would not make sense.
React will always re-render the component if the props change (if you don't implement custom shouldUpdate lifecycle method).

Resources