How to prevent Carousel from rerendering - reactjs

I am using React Grid Carousel in my app and have an images grid and a function that if an image in that grid is clicked it opens up a modal.
Here is some important bits of the code:
Parent component:
function parentComponent () {
return (
<section>
<div>
<h1>
Images
</h1>
</div>
<ChildComponent />
</section>
);
Child component:
function childComponent () {
const handleModal = useCallback(
e => {
setImageId(e.target.id);
setModalOpen(true);
},
[modalOpen, imageId]
);
}
const data = sectionData.map((data, i) => {
return data;
});
const items = data[0].map((item, i) => {
return (
<div id={i} onClick={e => handleModal(e)}>
<Image width={200} height={200} alt={item.name} />
</div>
);
});
return (
<Carousel
cols={2}
rows={3}
showDots
>
{items.map((item, i) => (
<Carousel.Item key={i}>
{item}
</Carousel.Item>
))}
</Carousel>
{modalOpen && <MemberModal/>}
);
The problem I am having is that if I am in let's say, page 2 of the modal, once I click in an image, the carousel goes back to the first page as the result of the rerender caused by the state change that happens on the handleModal.
I have tried React.memo this component and the parent too just in case and also using useCallback but nothing seems to work. I just simply cannot stop the rerender.
Any idea on how to accomplish stoping the rerender or sorting the issue at all?

React re-renders children components automatically after a state change. If your state is inside MyComponent it will re-render everything inside the return function.
But if you wrap the Carousel part of your component in memo, it will compare its props and if the props have not changed, it wont re-render the component.
const Example = ({ items }) => {
return (
<>
<Carousel
cols={2}
rows={3}
showDots
>
{items.map((item, i) => (
<Carousel.Item key={i}>
{item}
</Carousel.Item>
))}
</Carousel>
</>
);
};
export default React.memo(Example);

Related

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. cancel all subscriptions an

I am passing props from a child nested inside a class component
class Viewer extends React.Component {
....
render(){
return(
.....
<DragAndDrop characters={characters}/>
)
}
to the parent functional component
function DragAndDrop(props) {
console.log("char",props.characters); # I am able to console.log this
const [characters, updateCharacters] = useState(props.characters); # but doing this throws an error
function handleOnDragEnd(result) {
if (!result.destination) return;
const items = Array.from(characters);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
updateCharacters(items);
}
return (
<div className="App">
<header className="App-header">
<h1>Final Space Characters</h1>
<DragDropContext onDragEnd={handleOnDragEnd}>
<Droppable droppableId="characters">
{(provided) => (
<ul
className="characters"
{...provided.droppableProps}
ref={provided.innerRef}
>
{characters.map(({ id, name, thumb }, index) => {
return (
<Draggable key={id} draggableId={id} index={index}>
{(provided) => (
<li
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<div className="characters-thumb">
<img src={thumb} alt={`${name} Thumb`} />
</div>
<p>{name}</p>
</li>
)}
</Draggable>
);
})}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
</header>
</div>
);
}
export default DragAndDrop;
but when I pass props.characters to useState, it throw an error, How I can resolve this? thanks
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. cancel all subscriptions an
This problem take place because you initialize state before mount component.
If you want to correct your component you can use useEffect inside your component and inside that updateCharacters like below
useEffect(()=>{
updateCharacters(props.characters);
}, [])
Dependency array is required if you don't want the component rerendering infinitely

How to change a style of an HTML element in React?

I have two React components
class App extends React.Component {
render() {
return (
<div id="appWrapper">
<ConfigureWindow />
<button id="configureClocksButton">Configure clocks</button>
<section id="clocksHere"></section>
</div>
);
}
}
const ConfigureWindow = () => (
<div id="configureWindowWrapper">
<div id="configureWindow">
<section id="addCitySection">TODO: adding a city</section>
<div id="verticalLine"></div>
<section id="listOfCities">
<header>
<h1>Available cities</h1>
<div id="closeConfigureWindowWrapper">
<img src="..\src\images\exit.png" id="closeConfigureWindow" alt="" />
</div>
</header>
<section id="availableCities"></section>
</section>
</div>
</div>
);
I want "ConfigureWindow" to be shown when "configureClocksButton". I tried to execute it with props, state and a function but got errors. It also would be nice if you explain me how to create new React components with React functions?
You probably want to use the React.JS event onClick (https://reactjs.org/docs/handling-events.html), and a state to store the action. To create a function component, you just have to return the JSX you want to render, and use hooks (https://reactjs.org/docs/hooks-intro.html) and then do a conditional rendering (https://reactjs.org/docs/conditional-rendering.html):
const App = () => {
const [toggleConfiguration, setToggleConfiguration] = useState(false)
return (
<div id="appWrapper">
{toggleConfiguration && <ConfigureWindow />}
<button onClick{() => setToggleConfiguration(true)} id="configureClocksButton">Configure clocks</button>
<section id="clocksHere"></section>
</div>
);
}
It's a bit difficult to understand your post, but I gather you want to click the button with id="configureClocksButton" and conditionally render the ConfigureWindow component.
You can accomplish this with some boolean state, a click handler to toggle the state, and some conditional rendering.
class App extends React.Component {
this.state = {
showConfigureWindow: false,
}
toggleShowConfigureWindow = () => this.setState(prevState => ({
showConfigureWindow: !prevState.showConfigureWindow,
}))
render() {
return (
<div id="appWrapper">
{showConfigureWindow && <ConfigureWindow />}
<button
id="configureClocksButton"
onClick={this.toggleShowConfigureWindow}
>
Configure clocks
</button>
<section id="clocksHere"></section>
</div>
);
}
}
A function component equivalent:
const App = () => {
const [showConfigureWindow, setShowConfigureWindow] = React.useState(false);
const toggleShowConfigureWindow = () => setShowConfigureWindow(show => !show);
return (
<div id="appWrapper">
{showConfigureWindow && <ConfigureWindow />}
<button
id="configureClocksButton"
onClick={toggleShowConfigureWindow}
>
Configure clocks
</button>
<section id="clocksHere"></section>
</div>
);
}

Reset component into modal

I have a component that is inserted in a modal and that includes a CheckListBox. When the modal starts each time, the component is not reset. How can I do? How Force reset? I use reactjs with hooks.
How can I trigger a reset event every time the modal opens?
Thanks a lot.
const CheckList = ({title, api, color, onChange }) => {
const [items, setItems] = useState([]);
let listCheck = [];
useEffect(() => {
axiosApi.get( `${api}`).then((res)=>{
setItems(res.data);
})
}, [])
function handleClick(ev, item) {
if (ev.target.checked) {
listCheck.push(item)
onChange(listCheck);
}
else
{
listCheck = listCheck.filter(riga => {
return (riga.id !== item.id)});
onChange(listCheck);
}
}
return (
<>
<div class="card rd-card-list">
<div class="card-header">
{title}
</div>
<div class="card-content rd-card-content">
<div class="content rd-scroll">
<ul class="rd-ul">
{ items.map( (item) =>
<li class="rd-li" key={item.id}>
<label class="checkbox">
{item.description}
</label>
<input type="checkbox" onClick={(ev) => handleClick(ev, item)}/>
</li>
)
}
</ul>
</div>
</div>
</div>
</>
);
}
export default CheckList;
in my modal.js
<CheckList title="mytititle" api="/api/users" onChange={(itx) => {
formik.setFieldValue('users', itx)
} }/>
The easiest way is to not render the modal until it's open:
<div>
{modalOpen &&
<Modal open={modalOpen}>
<CheckList title="mytititle" api="/api/users" onChange={(itx) => {
formik.setFieldValue('users', itx)
} }/>
</Modal>
}
</div>
So whenever you close the modal, it will be removed from DOM, along with any data that this component had.
React life cycle events can be used to perform operation before a component can be rendered. 'constructor()' or 'componentDidMount()' can be used in class components to reset the data or any other operation before rendering the component.
Since you are using function component, you can use React hooks to mimic the life cycle events using 'useEffect()'.

How to pass Mobx store as props to react compoent

I have this app that uses mobx, in it there is a component called "Listings" that uses some state from mobx to render a list of items.
The way it is right now, is that the Listings component gets the data it needs(store.restaurantResults[store.selectedFood]) from inside of it by using the mobx store like so:
const Listings = () => {
const store = React.useContext(StoreContext);
return useObserver(() => (
<div className="pa2">
{store.restaurantResults[store.selectedFood] &&
store.restaurantResults[store.selectedFood].map((rest, i) => {
return (
<div key={i} className="pa2 listing">
<p>{rest.name}</p>
</div>
);
})}
</div>
));
};
But i think this is wrong, as it couples the component with the data, I want instead to pass that data via props so it can be reusable.
What is the correct way to do this? Right now my App looks like this, where it's being wrapped around a storeProvider:
function App() {
return (
<StoreProvider>
<div className="mw8 center">
<Header title="EasyLunch" subTitle="Find Pizza, Burgers or Sushi in Berlin the easy way"/>
<FixedMenu menuItem1={"Pizza"} menuItem2={"Burger"} menuItem3={"Sushi"} />
<p className="b tc pt3">or...</p>
<Search />
<Listings />
</div>
</StoreProvider>
);
}
My idea is to extract everrything inside the StoreProvider into another component that has a store and returns the jsx via useObserver so that I can acces the store and then pass what i need as props to the other components. like this:
const Wapper = () => {
const store = React.useContext(StoreContext);
return useObserver(() => (
<div className="mw8 center">
<Header title="EasyLunch" subTitle="Find Pizza, Burgers or Sushi in Berlin the easy way" />
<FixedMenu menuItem1={"Pizza"} menuItem2={"Burger"} menuItem3={"Sushi"} />
<p className="b tc pt3">or...</p>
<Search />
<Listings listings={store.restaurantResults[store.selectedFood]} />
</div>
))
}
And then on the listings component change the hard coded store.restaurantResults[store.selectedFood] inside to use the props that is being passes now, that is called listigs like so:
const Listings = ({listings}) => {
const store = React.useContext(StoreContext);
return useObserver(() => (
store.loading
? <Loading />
: <div className="pa2">
<div className="flex flex-wrap">
{listings &&
listings.map((rest, i) => {
return (
<div key={i} className="pa2 listing">
<img className='object-fit' src={rest.image_url} alt="restuarant" />
<p>{rest.name}</p>
<p>{rest.location.address1}</p>
</div>
);
})}
</div>
</div>
));
};
And this works, but is this the right way to go about this?
As <Listings/> can be provided with listing and loading you can:
const Listings = ({listings, loading}) => {
if(loading) return <Loading />
return (
<div className="pa2">
<div className="flex flex-wrap">
{listings && listings.map((rest, i) => {
return (
<div key={i} className="pa2 listing">
<img className='object-fit' src={rest.image_url} alt="restuarant" />
<p>{rest.name}</p>
<p>{rest.location.address1}</p>
</div>
);
})}
</div>
</div>
);
}
No observables used, no useObservable required.
You want to useObservables on store for listings then no reason to wrap all components with useObservable. You should wrap <Listings/> only.
I usually define my store as a global, so every component has visibility of it:
class Store {
#observable myVar
}
global.store = new Store()
And in my components i just use it:
#observer
export default class MyComponent extends React.Component {
constructor () {
super()
store.myVar = 0
}
setMyVar (a) {
store.myVar += 1
}
render () {
return <button onClick={this.setMyVar}>
Clicked {store.myVar} times
</button>
}
}

Logic for Three-dot more options menu for web applications in reactjs

I am new to ReactJs and I'm developing a social media web application. Here I have template where I have to implement a Three-dot more options menu. I tried using Bootstrap menu and react Bootstrap component menu. Both didn't work for me. What is the best way to implement this feature without using a library?
I did till toggling the menu. But on click, all the menus toggle altogether. I am not able do the toggling individually.
Here's the piece of code I did:
post.jsx
class UserPost extends Component {
state = {
overFlowMenuActive: false
};
toggleOverflowMenu = () => {
this.setState((prevState) => ({ overFlowMenuActive:
!prevState.overFlowMenuActive }));
};
closeOverflowMenu = () => {
this.setState({ overFlowMenuActive: false });
};
render() {
return (
<React.Fragment>
{this.props.posts.map((post, index) =>(
<div>
<div tabIndex='0' onBlur={this.closeOverflowMenu}>
<img src={require('../../assets/images/more.svg')} alt='' onClick={this.toggleOverflowMenu}/>
</div>
<MoreBtn options={this.state.options} overFlowMenuActive={this.state.overFlowMenuActive} />
</div>
))}
</React.Fragment>
);
}
MoreBtn.jsx
<div className={`${classes['popup-more']} ${this.props.overFlowMenuActive
? classes.expand
: classes.collapse}`}>
{this.props.options.map((option, index) => (
<div key={index}>
<img src={option.url} alt='' />
<p>{option.name}</p>
</div>
))}
</div>
You are maintaining only a single state for all UserPosts
To have each of these toggle seperately, these states should be moved into the component.
class SinglePost extends Component {
state = {
overFlowMenuActive: false
};
toggleOverflowMenu = () => {
this.setState((prevState) => ({ overFlowMenuActive:
!prevState.overFlowMenuActive }));
};
closeOverflowMenu = () => {
this.setState({ overFlowMenuActive: false });
};
render() {
return (
<div>
<div tabIndex='0' onBlur={this.closeOverflowMenu}>
<img src={require('../../assets/images/more.svg')} alt='' onClick={this.toggleOverflowMenu}/>
</div>
<MoreBtn options={this.state.options} overFlowMenuActive={this.state.overFlowMenuActive} />
</div>
);
}
class UserPost extends Component {
render() {
return (
<React.Fragment>
{this.props.posts.map((post, index) =>(
<SinglePost post={post} />
))}
</React.Fragment>
);
}
This way, the button for only one component is toggled at a time

Resources