State leaking between React sibling components - javascript

I'm having an issue with React passing state between sibling components when one of the siblings is deleted.
In my program, each component Plant has a state "watered", which has a default of "", and can be updated to the current day by pressing a button. When I delete a plant that has a non-empty watered state, that state passes to the next plant component.
I am sure that the correct item is being deleted by directly monitoring the keys in the parent.
Does this have something to do with a memory leak? Is there some code I can add to componentWillUnmount() method to solve this?
Thanks!
Edit:
My Plant class
class Plant extends React.Component {
state = {
watered : "",
note: "",
animate : "",
modalState: false
};
noteRef = React.createRef()
water = e => {
this.toggleAnimation()
const date = new Date();
const formatDate = date.getMonth().toString().concat('/', date.getDate())
this.setState({watered : formatDate})
}
toggleAnimation = () => {
this.setState({animate : "shake"});
setTimeout(() => {
this.setState({animate : ""})
}, 500);
}
componentDidMount() {
this.toggleAnimation()
}
componentWillUnmount() {
}
addNote = () => {
this.setState({modalState : true})
}
hideModal = () => {
const msg = "Variety : ".concat(this.noteRef.current.value)
this.setState({note:msg})
this.setState({modalState : false })
}
render() {
return (
<div>
<Modal show={this.state.modalState}>
<Modal.Header>Enter a variety for your plant!</Modal.Header>
<Modal.Body>
<input type="text" ref={this.noteRef} placeholder="Variety"/>
</Modal.Body>
<Modal.Footer>
<button onClick={this.hideModal}>Save</button>
</Modal.Footer>
</Modal>
<Card className={"plant-card".concat(this.state.animate)} >
<Card.Body className="card-body">
<Card.Title className="plant-card-title">
<span className="plant-card-title">{this.props.name}</span>
</Card.Title>
</Card.Body>
<Card.Text>
{this.state.note}
{this.state.watered}
<Container className="icon-div">
<img src={"images/watering-can.png"}
className="small-icon"
alt="can"
onClick={this.water}/>
<img src={"images/shovel.png"}
className="icon"
alt="shovel"
onClick={() => this.props.removeFromGarden(this.props.index)}/>
<img src={"images/grain-bag.png"}
className="icon"
alt="bag"
onClick={() => this.props.addHarvests(this.props.name, 1)}/>
<img src={"images/wheelbarrow.png"}
className="small-icon"
alt="bag"
onClick={this.addNote}/>
</Container>
</Card.Text>
</Card>
</div>
) }
export default Plant;`
Removing a plant from state in my App component (main parent)
removeFromGarden = key => {
const garden = {...this.state.garden };
delete garden[key]
this.setState({garden })
}

This might occur if you're using an index as a key of the components in the array. Make sure that after deleting an element, all remaining elements preserve their original keys - if not, react will interpret the next element as the deleted one.

Related

Toggle only the menu clicked in Reactjs

I am making a menu and submenus using recursion function and I am in the need of help to open only the respective menu and sub menu's..
For button and collapse Reactstrap has been used..
Recursive function that did menu population:
{this.state.menuItems &&
this.state.menuItems.map((item, index) => {
return (
<div key={item.id}>
<Button onClick={this.toggle.bind(this)}> {item.name} </Button>
<Collapse isOpen={this.state.isToggleOpen}>
{this.buildMenu(item.children)}
</Collapse>
</div>
);
})}
And the buildMenu function as follows,
buildMenu(items) {
return (
<ul>
{items &&
items.map(item => (
<li key={item.id}>
<div>
{this.state.isToggleOpen}
<Button onClick={this.toggle.bind(this)}> {item.name} </Button>
<Collapse isOpen={this.state.isToggleOpen}>
{item.children && item.children.length > 0
? this.buildMenu(item.children)
: null}
</Collapse>
</div>
</li>
))}
</ul>
);
}
There is no problem with the code as of now but I am in the need of help to make menu -> submenu -> submenu step by step open and closing respective levels.
Working example: https://codesandbox.io/s/reactstrap-accordion-9epsp
You can take a look at this example that when you click on any menu the whole level of menus gets opened instead of clicked one..
Requirement
If user clicked on menu One, then the submenu (children)
-> One-One
needs to get opened.
And then if user clicked on One-One,
-> One-One-One
-> One - one - two
-> One - one - three
needs to get opened.
Likewise it is nested so after click on any menu/ children their respective next level needs to get opened.
I am new in react and reactstrap way of design , So any help from expertise would be useful for me to proceed and learn how actually it needs to be done.
Instead of using one large component, consider splitting up your component into smaller once. This way you can add state to each menu item to toggle the underlying menu items.
If you want to reset al underlying menu items to their default closed position you should create a new component instance each time you open up a the underlying buttons. By having <MenuItemContainer key={timesOpened} the MenuItemContainer will be assigned a new key when you "open" the MenuItem. Assigning a new key will create a new component instance rather than updating the existing one.
For a detailed explanation I suggest reading You Probably Don't Need Derived State - Recommendation: Fully uncontrolled component with a key.
const loadMenu = () => Promise.resolve([{id:"1",name:"One",children:[{id:"1.1",name:"One - one",children:[{id:"1.1.1",name:"One - one - one"},{id:"1.1.2",name:"One - one - two"},{id:"1.1.3",name:"One - one - three"}]}]},{id:"2",name:"Two",children:[{id:"2.1",name:"Two - one"}]},{id:"3",name:"Three",children:[{id:"3.1",name:"Three - one",children:[{id:"3.1.1",name:"Three - one - one",children:[{id:"3.1.1.1",name:"Three - one - one - one",children:[{id:"3.1.1.1.1",name:"Three - one - one - one - one"}]}]}]}]},{id:"4",name:"Four"},{id:"5",name:"Five",children:[{id:"5.1",name:"Five - one"},{id:"5.2",name:"Five - two"},{id:"5.3",name:"Five - three"},{id:"5.4",name:"Five - four"}]},{id:"6",name:"Six"}]);
const {Component, Fragment} = React;
const {Button, Collapse} = Reactstrap;
class Menu extends Component {
constructor(props) {
super(props);
this.state = {menuItems: []};
}
render() {
const {menuItems} = this.state;
return <MenuItemContainer menuItems={menuItems} />;
}
componentDidMount() {
loadMenu().then(menuItems => this.setState({menuItems}));
}
}
class MenuItemContainer extends Component {
render() {
const {menuItems} = this.props;
if (!menuItems.length) return null;
return <ul>{menuItems.map(this.renderMenuItem)}</ul>;
}
renderMenuItem(menuItem) {
const {id} = menuItem;
return <li key={id}><MenuItem {...menuItem} /></li>;
}
}
MenuItemContainer.defaultProps = {menuItems: []};
class MenuItem extends Component {
constructor(props) {
super(props);
this.state = {isOpen: false, timesOpened: 0};
this.open = this.open.bind(this);
this.close = this.close.bind(this);
}
render() {
const {name, children} = this.props;
const {isOpen, timesOpened} = this.state;
return (
<Fragment>
<Button onClick={isOpen ? this.close : this.open}>{name}</Button>
<Collapse isOpen={isOpen}>
<MenuItemContainer key={timesOpened} menuItems={children} />
</Collapse>
</Fragment>
);
}
open() {
this.setState(({timesOpened}) => ({
isOpen: true,
timesOpened: timesOpened + 1,
}));
}
close() {
this.setState({isOpen: false});
}
}
ReactDOM.render(<Menu />, document.getElementById("root"));
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactstrap/8.4.1/reactstrap.min.js"></script>
<div id="root"></div>
You will want to create an inner component to manage the state at each level.
For example, consider the following functional component (I'll leave it to you to convert to class component):
const MenuButton = ({ name, children }) => {
const [open, setOpen] = useState(false);
const toggle = useCallback(() => setOpen(o => !o), [setOpen]);
return (
<>
<Button onClick={toggle}>{name}</Button>
<Collapse open={open}>{children}</Collapse>
</>
);
};
This component will manage whether to display its children or not. Use it in place of all of your <div><Button/><Collapse/></div> sections, and it will manage the open state for each level.
Keep shared state up at the top, but if you don't need to know whether something is expanded for other logic, keep it localized.
Also, if you do need that info in your parent component, use the predefined object you already have and add an 'open' field to it which defaults to false. Upon clicking, setState on that object to correctly mark the appropriate object to have the parameter of true on open.
Localized state is much cleaner though.
Expanded Example
import React, { Component, useState, useCallback, Fragment } from "react";
import { Collapse, Button } from "reactstrap";
import { loadMenu } from "./service";
const MenuButton = ({ name, children }) => {
const [open, setOpen] = React.useState(false);
const toggle = useCallback(() => setOpen(o => !o), [setOpen]);
return (
<Fragment>
<Button onClick={toggle}>{name}</Button>
<Collapse open={open}>{children}</Collapse>
</Fragment>
);
};
class Hello extends Component {
constructor(props) {
super(props);
this.state = {
currentSelection: "",
menuItems: [],
};
}
componentDidMount() {
loadMenu().then(items => this.setState({ menuItems: items }));
}
buildMenu(items) {
return (
<ul>
{items &&
items.map(item => (
<li key={item.id}>
<MenuButton name={item.name}>
{item.children && item.children.length > 0
? this.buildMenu(item.children)
: null}
</MenuButton>
</li>
))}
</ul>
);
}
render() {
return (
<div>
<h2>Click any of the below option</h2>
{this.state.menuItems &&
this.state.menuItems.map((item, index) => {
return (
<MenuButton name={item.name}>
{this.buildMenu(item.children)}
</MenuButton>
);
})}
</div>
);
}
}
export default Hello;

Toggle font-awesome icon on click in react

I want to toggle font awesome icons on click. When the page is loaded i query the backend and find out whether a user is enrolled into a course or not, incase they are enrolled I show a tick icon, otherwise I show a coffee icon.
The end goal is have each individual icon change into the opposite when clicked. Currently when i click the icons, for example if i click a cup icon it not only changes into a tick but changes the rest of the cup icons into ticks too. How can I resolve this issue so that when clicked, only the clicked icon is affected?
Here is my code
Functional component
export const CourseCard = ({
video,
normaluser,
adminuser,
userauthenticated,
adminauthenticated,
handleUnroll,
handleEnroll,
enrolled,
unrolled
}) => (
<Grid item xs={6} md={4} lg={3}>
{(video.enrolled_students.includes(normaluser) &&
userauthenticated) ||
(video.enrolled_students.includes(adminuser) &&
adminauthenticated) ? (
<div className="enrol__button">
<div>
<a href="#" onClick={() => handleUnroll(video.slug)}>
<FontAwesomeIcon
icon={enrolled ? faCheckSquare : faCoffee}
/>
</a>
</div>
</div>
) : (!video.enrolled_students.includes(normaluser) &&
userauthenticated) ||
(!video.enrolled_students.includes(adminuser) &&
adminauthenticated) ? (
<div>
<a href="#" onClick={() => handleEnroll(video.slug)}>
<FontAwesomeIcon
icon={unrolled ? faCoffee : faCheckSquare}
/>
</a>
</div>
) : (
""
)}
</Grid>
Container
export class AllCourses extends React.Component {
constructor(props) {
super(props);
this.user = details(AUTHENTICATED);
this.admin = AdminDetails(AUTHENTICATED);
const token = localStorage.getItem("token");
let normaldetail = details(token);
this.normaluser = normaldetail.user_id;
let admindetail = AdminDetails(token);
this.adminuser = admindetail.user_id;
this.state = {
enrolled: true,
unrolled: true
};
}
handleEnroll = slug => {
this.props.dispatch(Enroll(slug));
this.setState({unrolled: !this.state.unrolled});
}
handleUnroll = slug => {
this.props.dispatch(Enroll(slug));
this.setState({enrolled: !this.state.enrolled});
}
render() {
const userauthenticated = this.user;
const adminauthenticated = this.admin;
const adminuser = this.adminuser;
const normaluser = this.normaluser;
const { allCourses } = this.props;
const {search, enrolled, unrolled} = this.state;
return (
<div className="container">
<Grid
container
spacing={3}
className="courses__row courses__row__medium"
>
{allCourses.map(video => (
<CourseCard
key={video.slug}
video={video}
enrolled={enrolled}
unrolled={unrolled}
handleEnroll={this.handleEnroll}
handleUnroll={this.handleUnroll}
normaluser={normaluser}
adminuser={adminuser}
userauthenticated={userauthenticated}
adminauthenticated={adminauthenticated}
/>
))}
;
</Grid>
</div>
);
}
You can instead a conditional on a boolean try to compare current card key to checked card key
<FontAwesomeIcon icon={this.props.checkedCard == this.props.key ? faCoffee : faCheckSquare} />
and in your container :
handleEnroll = slug => {
this.props.dispatch(Enroll(slug));
this.setState({checked: this.props.key});
}
and :
<CourseCard
key={video.slug}
video={video}
checkedCard={this.state.checkedCard}
It's because handleEnroll and handleUnroll set state that is shared across all the courses. From what you described it sounds like you want the state to actually be per course.
So you should alter AllCourses slightly
handleEnroll = slug => {
// This should cause some change to the relevant course in allCourses
this.props.dispatch(Enroll(slug));
}
handleUnroll = slug => {
// This should cause some change to the relevant course in allCourses
this.props.dispatch(Enroll(slug));
}
// Delete this
this.state = {
enrolled: true,
unrolled: true
};
And then change the CourseCard mapping to use the properties from video rather than the ,now eliminated, AllCourses state.
{allCourses.map(video => (
<CourseCard
key={video.slug}
video={video}
enrolled={video.enrolled}
unrolled={video.unrolled}
handleEnroll={this.handleEnroll}
handleUnroll={this.handleUnroll}
normaluser={normaluser}
adminuser={adminuser}
userauthenticated={userauthenticated}
adminauthenticated={adminauthenticated}
/>
))}
Since you're checking in the Grid component whether the current user is enrolled or not (by seeing if that video.enrolled_students array includes the current user), then those enrolled and unrolled flags don't seem necessary anymore.
So in Grid you should be able to change the first <FontAwesomeIcon /> call to just:
<FontAwesomeIcon icon='faCheckSquare' />
and the second one to
<FontAwesomeIcon icon='faCoffee' />
Also, you have a typo in AllCourses where you're calling this.props.dispatch(Enroll(slug)); in both handleEnroll and handleUnroll where it should most probably be Unroll(slug) in the second one.

data does not re-render after clicking the sort button

I have milestoneCards.
I want to add a sort button, that upon clicking this button the cards will be sorted by the card heading.
The sort takes place, but it does not re-render the list in the sorted order.
please advise.
thank you so much for helping me here.
import React from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { Card, CardBody, CardTitle } from "reactstrap";
const MyMilestones = props => {
let sortClicked = false;
let milestoneCards =
props.milestones.length > 0
? props.milestones.map(m => (
<p key={m.id}>
<Link to={`/milestones/${m.id}`}>{m.attributes.heading}</Link>
</p>
))
: null;
const sortedMilestoneCards = [...props.milestones]
.sort((a, b) => (a.attributes.heading > b.attributes.heading ? 1 : -1))
.map(m => (
<p key={m.id}>
<Link to={`/milestones/${m.id}`}>{m.attributes.heading}</Link>
</p>
));
return (
<div className="MilestoneCards">
{
<Card>
<CardBody>
<CardTitle>
<h4>My Milestones</h4>
</CardTitle>
<button
onClick={() => {
sortClicked = true;
console.log("before", milestoneCards);
milestoneCards = sortedMilestoneCards;
console.log("after", milestoneCards);
return (milestoneCards = sortedMilestoneCards);
}}
>
Sort
</button>
sortClicked ? ({sortedMilestoneCards}) : {milestoneCards}
</CardBody>
</Card>
}
</div>
);
};
const mapStateToProps = state => {
return {
milestones: state.myMilestones
};
};
export default connect(mapStateToProps)(MyMilestones);
It's because you need to have sortClicked to be tracked by React.
When let sortClicked = false is declared inside MyMilestones component, it's declared once on the first component mount and won't be updated when the component is re-rendered.
So you can save sortClicked in a state using React.useState and update it onClick. useState is a one-off way of storing this.state value for Class Component but for one state. (I won't get into it too deep as React documentation has a thorough coverage on Introducing Hooks)
const MyMilestones = props => {
// let sortClicked = false;
// Initialize it to "false" by default.
let [sortClicked, setSortClicked] = React.useState(false)
let milestoneCards = ...;
const sortedMilestoneCards = ...;
return (
<div className="MilestoneCards">
{
<Card>
<CardBody>
<CardTitle>
<h4>My Milestones</h4>
</CardTitle>
<button
onClick={() => {
// Notify "React" to re-render.
setSortClicked(true)
// No need to return a new reference here.
}}
>
Sort
</button>
{/* 👇 Note that {} is wrapped around the whole block. */}
{sortClicked ? sortedMilestoneCards : milestoneCards}
</CardBody>
</Card>
}
</div>
);
};
It's because you're not updating the milestones correctly. Since they're stored on Redux state, you need to add and dispatch the action that modifies the state.
I recommend you look at the Redux documentation.

render displaySIngleElement component onClick react

I am pretty new to react and I have been stuck in a problem for quite a good time.
I have a component DisplayList that iterates through an array of objects and displays them in a list form. Each object becomes a button. I also have another component to render the single view of each item on the list once the item is clicked. My problem is that I get to render the single view of all my items at once INSIDE my displayList component. All I want is to be able to click on the list item and render another component with ONLY info about the item I clicked on and passing my "project" as the props to it. what should I do? What is my error?
My DisplayList component (the part that matters for this problem):
export default class DisplayList extends Component {
constructor() {
super();
this.state = {
displaySingle: false
};
}
handleClick = () => {
this.setState({
displaySingle: true
})
}
render() {
if (this.props.projects && this.props.projects.length > 0) {
return (
<List component="nav">
{this.props.projects.map(project => (
<div className="all-content-wrapper" key={project.id}>
<ListItem button value={project} onClick={this.handleClick}>
{this.state.displaySingle ?
<DisplaySingleItem project={project} /> :
null
}
<ListItemICon>
<img
className="single-item-img-in-list-view"
src={project.img}
/>
</ListItemICon>
You are just a hint away from doing it the right way:
Change the condition in your onClick() as:
onClick={()=>this.handleClick(project.id)}
{ this.state.displayProject_id === project.id ?
<DisplaySingleItem project={project} /> :
null
}
Now define handleClick() as:
handleClick = (project_id) => {
this.setState({
displayProject_id: project_id
})
}
Don't forget to define the initial state in the constructor:
this.state = {
displayProject_id:null
};
<div className="all-content-wrapper" key={project.id}>
<ListItem button value={project} onClick={()=>this.handleClick(project)}>
{this.state.displayProject && this.state.displayProject.id==project.id ?
<DisplaySingleItem project={project} /> :
null
}
<ListItemICon>
<img
className="single-item-img-in-list-view"
src={project.img}
/>
</ListItemICon>
</ListItem>
</div>
change your JSX like the above so you pass the current project to handleClick and change handleClick like the following.
handleClick = (project) => {
this.setState({
displayProject : project
})
}
It should now display the <DisplaySingleItem/> for the clicked project.
For you to be able to show only the project that was selected it is important that you have a reference to it. Right now your handleClick() function does not accept and parameters or data that you can identify the project that was selected.
My solution for you is to pass the project as a parameter to handleClick(project). So your code should look like.
export default class DisplayList extends Component {
constructor() {
super();
this.state = {
displaySingle: false
};
}
handleClick = (project) => {
this.setState({
selectedProject: project, // <- use this state to show your popup or
// whatever view you're using
displaySingle: true
})
}
render() {
if (this.props.projects && this.props.projects.length > 0) {
return (
<List component="nav">
{this.props.projects.map(project => (
<div className="all-content-wrapper" key={project.id}>
<ListItem button value={project} onClick={() => this.handleClick(project)}>
{this.state.displaySingle ?
<DisplaySingleItem project={project} /> :
null
}
<ListItemICon>
<img
className="single-item-img-in-list-view"
src={project.img}
/>
</ListItemICon>
)
}

React Component State issue with duplicate components

I've recently started learning React and I'm a little bit confused.
Please see the following codepen or the code snippet below.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
sessions: [],
sessionSelected: null
}
this.addSession = this.addSession.bind(this);
this.switchSession = this.switchSession.bind(this);
}
addSession() {
let sessions = this.state.sessions;
let id = (sessions.length)
let title = "Session " + id;
let session = <Session title={title} index={id + 1} />;
sessions.push(session);
this.setState({
sessions: sessions,
sessionSelected: id
});
}
switchSession(id) {
this.setState({
sessionSelected: id
});
}
render() {
return (
<div>
<button onClick={this.addSession} >+ Add Session</button>
<div>{this.state.sessions[this.state.sessionSelected]}</div>
<div className="switchers">
{this.state.sessions.map((x, i) => {
return <SessionSwitcher index={i + 1} onClick={() => { this.switchSession(i) }} />;
})}
</div>
</div>
);
}
}
class Session extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
this.startTimer = this.startTimer.bind(this);
this.count = this.count.bind(this);
}
startTimer() {
setInterval(this.count, 1000);
}
count() {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.state.count}</p>
<button onClick={this.startTimer}>Start Timer</button>
</div>
)
}
}
class SessionSwitcher extends React.Component {
render() {
return (
<div className="switcher" onClick={this.props.onClick}>
<span>{this.props.index}</span>
</div>
)
}
}
ReactDOM.render(
<App />,
document.querySelector('#app')
);
I want to be able to trigger multiple timers within multiple components.
For some reason when I click the start timer in one component, it triggers it for the other components too.
Can someone explain to me what I am doing wrong?
Here are a couple of things you could change to get a more predictable experience:
Rather than storing JSX in state, which is a complex object, store just the id, and render JSX according to that id.
Try not to mutate state in place (as with pushing onto an array that's already in state).
If you want to have persistent timers across components, regardless of which ones are currently selected, be sure not to unmount them when they're deselected.
Here are the relevant updated parts of your <App/> component (note that these are more quick fixes than best practices):
addSession() {
const id = this.state.sessions.length;
this.setState( state => ({
// treat your state as immutable
sessions: state.sessions.concat( id ),
sessionSelected: id
}));
}
// don't unmount when switching components, just hide
render() {
return (
<div>
<button onClick={this.addSession} >+ Add Session</button>
<div>
{ this.state.sessions.map( session =>
<div style={{ display: session === this.state.sessionSelected ? 'block' : 'none' }}>
<Session title={"Session " + session} />
</div>
)}
</div>
<div className="switchers">
{this.state.sessions.map((x, i) => {
return <SessionSwitcher index={i + 1} onClick={() => { this.switchSession(i) }} />;
})}
</div>
</div>
);
}
Try it here: https://codepen.io/glortho/pen/ZrLMda?editors=0011

Categories

Resources