Child component not updating when parent state changes - javascript

I have the following child component:
class Adjust extends Component {
render() {
const { values, toggleSelector, SELECTOR } = this.props;
console.log("values are", values"); //this is only being entered once right now
return(
<div
key={values}
style={{
marginBottom: "25px",
width: "80vw",
}}>
<button
buttonSelected={values[index]?.add}
onClick={() => {
toggleSelector(index, SELECTOR.ADD);
}}
>
"Add"
</button>
</div>
)}}
And this is how I pass props to this child
<Adjust values={values} SELECTOR={SELECTOR} toggleSelector={this.toggleSelector}> </Adjust>
I have a console log in my toggleSelector function in my parent component, which shows that it is being entered, but even though the state is changing, the render of Adjust component is not being entered again.
I have tried adding a key to it but that didn't help.
This is the toggleSelector function
toggleSelector(index, selector) {
console.log("enter");
let { values } = this.state;
values[index][selector] = true;
if (selector === SELECTOR.ADD) {
values[index].subtract = false;
} else if (selector === SELECTOR.SUBTRACT) {
values[index].add = false;
}
this.setState({
values,
});
}
This was all working fine when Adjust was not a child component but within the parent. Had to make it a child for better code readability

You don't manage values like an immutable variable, values is the same array between renders, you only update it's content.
You can find more information there Correct modification of state arrays in React.js

Related

React child component state is lost after parent component re-renders

I am using a React hook for parent/child component.
Now I have state in my parent component (companyIcon), which I need to update based on some validation in the child component. I pass validationCallback as a callback function to the child component and update my parent state based on the value I get from the child.
Now the issue is after I update the parent state, the state value in my child component gets reset. What I am doing wrong in the below implementation ?
function ParentComp(props) {
const [companyIcon, setCompanyIcon] = useState({ name: "icon", value: '' });
const validationCallback = useCallback((tabId, hasError) => {
if (hasError) {
setCompanyIcon(prevItem => ({ ...prevItem, value: 'error'}));
// AFTER ABOVE LINE IS EXECUTED, my Child component state "myAddress" is lost i.e. it seems to reset back to empty value.
}
}, []);
const MyChildCmp = (props) => {
const [myAddress, setmyAddress] = useState('');
useEffect(() => {
if (myAddressExceptions.length > 0) {
props.validationCallback('MyInfo', true);
} else {
props.validationCallback('MyInfo', false);
}
}, [myAddressExceptions])
const handlemyAddressChange = (event) => {
//setmyAddress(event.target.value);
//setmyAddressExceptions(event.target.value);
console.log(myAddressExceptions);
}
return (
<>
<div className="row" style={{ display: 'flex', flexDirection: 'row', width: '1000px'}}>
<div style={{ width: '20%'}}>
<FormField
label='Company Address'
required
helperText={mergedErrorMessages(myAddressExceptions)}
validationState={
myAddressExceptions[0] ? myAddressExceptions[0].type : ''
}
>
<Input id='myAddress'
value={myAddress}
//onChange={handlemyAddressChange}
onChange={({ target: { value } }) => {
validateInputValue(value);
}}
onBlur={handleBlur}
inputProps={{maxLength: 9}} />
</FormField>
</div>
</div>
</>
);
}
return (
<div className="mainBlock">
Parent : {companyIcon}
{displayMyChild && <MyChildCmp validationCallback={validationCallback}/>}
</div>
)
}
export default withRouter(ParentComp);
Here are some reasons why you can lose state in child (there could be more, but these apply to you most):
{displayMyChild && <MyChildCmp validationCallback={validationCallback}/>}
Here if at one point displayMyChild is truthy, then made falsy, this means the component MyChildCmp will get unmounted, hence all its state will be gone.
But now, even if you didn't have that condition and rendered the MyChildCmp always you would still run into similar problem, this is because you defined MyChildCmp inside another component. When you do that, on each render of the parent component, the function MyChildCmp is recreated, and the reconciliation algorithm of react thinks you rendered a different component type on next render, so it will destroy the component instance. Move definition of that component outside the parent component.

React toggle class on just one component

I'm creating, in componentDidMount, a lots of <div>'s.
constructor (props) {
super(props)
this.state = {
componentLoaded: false,
divs: []
}
}
componentDidMount () {
this.createDivs()
}
createDivs () {
// Actually, this divs are created dinamically and with infinite scroll
let divs = <div className='container'>
<div className='item' onClick={() => { /* Add class */ }}>...</div>
<div className='item' onClick={() => { /* Add class */ }}>...</div>
<div className='item' onClick={() => { /* Add class */ }}>...</div>
/* ... n divs ... */
</div>
let newDivs = this.state.divs
newDivs.push(divs)
this.setState({
componentLoaded: true,
divs: newDivs
})
}
render () {
return {this.state.componentLoaded ? this.state.divs : null }
/* In my return, if X event occurs, re-call this.createDivs() to add more divs */
}
What I'm trying to achieve, is to toggle a class into only one of the .item divs, and then if clicking another one, remove it from the before and add it to the one was clicked.
I've tried to add an attribute to the state, but it didn't add it. I also searched for some solutions, but I always find solutions which doesn't toggle, as they are "toggled individually" in separated components.
Hoping to find some help, maybe this thing is real simple, but for now, I cannot figure out how to make it.
PS: I'm adding the createDivs into the state because it's an infinite scroll that re-uses the function, so I just push them into the state and the scroll won't go to the top again when adding the previous ones + the new ones.
In problems like these it is always helpful to determine what goes into react's state. You want the state to be as lightweight as possible (so you store only the stuff which is necessary)
class Test extends React.Component {
state = {
selectedDiv: null,
};
handleClick = id => {
this.setState(prev => ({
// sets it to null if its already active else, sets it active
selectedDiv: prev.selectedDiv === id ? null : id,
}));
};
render() {
// Array to map over
const divs = [1, 2, 3, 4];
const { selectedDiv } = this.state;
return (
<div className="container">
{divs.map(div => {
return (
<div
key={div}
className={selectedDiv === div ? "item class_to_add" : "item"}
onClick={() => this.handleClick(div)}
>Item {div}</div>
);
})}
</div>
);
}
}
In the above examples we are only storing the unique Id of the div in the state and using that to determine if the selected div is active or not, if it is then we simply remove it from the state. The above solution does not require any complex lifecycle methods, my advice would be to keep the component as simple as possible.
PS. not part of the answer but I suggest you to look into the newer hooks API its more intuitive and most probably the future of react
First, note that you're breaking a React rule here:
this.state.divs.push(divs)
You must never directly modify state. The correct thing there is either:
this.setState({divs}); // Replaces any previous ones
or
this.setState(({divs: oldDivs}) => {divs: [...oldDivs, divs]}); // Adds to any previous ones
However, the "React way" to do this would probably be not to store those divs in state at all; instead, store the information related to them in state, and render them (in render) as needed, with the appropriate classes. The information about which one of them has the class would typically either be information on the items themselves, or some identifying information about the item (such as an id of some kind) held in your component's state.
Here's an example using items that have an id:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
// No items yet
items: null,
// No selected item yet
selectedId: null
};
}
componentDidMount() {
this.createDivs();
}
createDivs() {
// Simulate ajax or whatever
setTimeout(() => {
const items = [
{id: 42, label: "First item"},
{id: 12, label: "Second item"},
{id: 475, label: "third item"},
];
this.setState({items});
}, 800);
}
render () {
const {items, selectedId} = this.state;
if (!items) {
// Not loaded yet
return null;
}
return (
<div className='container'>
{items.map(({id, label}) => (
<div
key={id}
className={`item ${id === selectedId ? "selected" : ""}`}
onClick={() => this.setState({selectedId: id})}
>
{label}
</div>
))}
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById("root"));
.selected {
color: green;
}
.item {
cursor: pointer;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

React refs in memory game

Hi I'm a beginner in ReactJS and I'm making a memory game with it and have problems with revealing tiles.
I wanted to have a few values in parent component's state, like firstPick, secondPick, pickCount and also isHidden (this toggles icon visibility).
But putting it in parent component makes click on any button toggle icon on every tile. To solve this, I moved isHidden property to Button (child) component. Now i wanted to manipulate state of Button from its parent component, so I found information about using refs somewhere in the internet. But using them makes clicking every button only toggle the last button in the container. I suppose i messed up something.
So my Button components looks like this:
class Button extends Component {
state = {isHidden: true};
toggleHidden () {
this.setState({isHidden: !this.state.isHidden});
}
render() {
return (
<div>
<button className="tile" onClick={this.props.onClick}>
<i
className={this.props.icon}
style={
this.state.isHidden ? { display: "none" } : { display: "block" }
}
/>
</button>
</div>
);
}
}
and my Board components looks like this:
class Board extends Component {
state = { firstPick: "", secondPick: "", pickCount: 0 };
constructor(props) {
super(props);
this.buttonElement = React.createRef();
}
handleClick = () => {
this.buttonElement.current.toggleHidden();
this.setState({
firstPick: this.icon,
pickCount: this.state.pickCount + 1
});
alert(this.state.firstPick);
};
render() {
return (
<div className="board">
<div className="container">
<div className="row align-items-start">
<div className="col-3">
<Button
ref={this.buttonElement}
icon={animalArray[0]}
onClick={this.handleClick}
/>
Of course there are 11 other Button components here, but they look just the same. (Btw is there a way to not repeat this code? They are placed in bootstrap container).
I also have 1 bonus question. Is there a way to set the state.firstPick to the icon property? I don't know how to refer to this value from the Parent component method. I tried writing this.icon, but i don't think it works. I wanted to keep two choices in state variables and then compare them. Or is there maybe a better way to solve this problem? Thanks
Why not just handle the toggle in the button itself?
class Button extends Component {
state = {isHidden: true};
toggleHidden () {
this.setState({isHidden: !this.state.isHidden});
}
onClick = () => {
this.toggleHidden();
if (this.props.onClick) {
this.props.onClick();
}
}
render() {
return (
<div>
<button className="tile" onClick={this.onClick}>
<i
className={this.props.icon}
style={
this.state.isHidden ? { display: "none" } : { display: "block" }
}
/>
</button>
</div>
);
}
}
Update: To preserve unique reference for firstPick, you can wrap your handleClick in another function:
handleClick = (icon) => () => {
this.buttonElement.current.toggleHidden();
this.setState({
firstPick: icon,
pickCount: this.state.pickCount + 1
});
alert(this.state.firstPick);
};
render() {
return (
<div className="board">
<div className="container">
<div className="row align-items-start">
<div className="col-3">
<Button
ref={this.buttonElement}
icon={animalArray[0]}
onClick={this.handleClick(animalArray[0])}
/>
handleClick now becomes a function that returns your original function (with some extra/unique context, in this case animalArray[0]).
I would say the complexity of your project is enough to warrant a store like flux or redux to keep track of all your button properties. This is generally the solution to complex relationships between parent and child elements.
In my opinion, refs should only be used for uncontrolled components, that is, any elements on your page that are not in react.

ReactJS Wrong Component gets removed from DOM

I have three files: ShopsContainer.js ShopsComponent.js and ShopsItemComponent.js
ShopsContainer maintains an array of shop items in local state that gets passed down into ShopsComponent as props. ShopsComponent then maps through the items array that is being received as props and renders a ShopsItemComponent for each item in the array.
Within my ShopsContainer file, I have a method that removes a shop item from state using the following code:
removeShop = (shopAccount) => {
this.setState(prevState => ({
items: prevState.items.filter(shop => {
return shop.shopAccount !== shopAccount
})
}));
}
When this happens, the correct item is removed from the items array in state, however, whatever the last ShopItem is that is in the DOM at the time of the removeShop call will get removed no matter if it is the correct item that should be removed or not. In other words, when removeShop gets called and the items array in state gets updated correctly, the wrong ShopItemComponent gets removed from the DOM.
What I would like to happen (or what I think should happen) is when removeShop gets called, that shop gets removed from the items array in state and ShopsContainer re-renders causing ShopsComponent to re-render with the updated props being received. And lastly ShopsComponent would map through the newly updated items array in props displaying a `ShopItemComponent for the correct items. Perhaps the problem has to do with the props being updated?
My code is as follows:
ShopsContainer.js
class ShopsContainer extends Component {
constructor() {
this.state = {
items: null
}
this.getAll();
this.removeShop = this.removeShop.bind(this);
}
getAll = () => {
// API request that fetches items and updates state
}
removeShop = (shopAccount) => {
this.setState(prevState => ({
items: prevState.items.filter(shop => {
return shop.shopAccount !== shopAccount
})
}));
}
render() {
return (
<div>
{this.state.items ? <ShopComponent items={this.state.items} removeShop={this.removeShop} /> : <div><h1>Loading...</h1></div>}
</div>
);
}
}
ShopsComponent.js
class ShopsComponent extends Component {
constructor() {
this.handleRemove = this.handleRemove.bind(this);
}
handleRemove = (shopAccount) => {
this.props.removeShop(shopAccount);
}
render() {
return (
<React.Fragment>
<Header />
{this.props.items.map((shopItem, i) => {
return (<ShopItemComponent key={i} item={shopItem} removeShop={this.handleRemove} />);
})}
</React.Fragment>
);
}
}
Your code is working great, but you only has one mistake , your ShopComponent is assign index as a key for each ShopItemComponent and react is tracking those indexes to update the correct component, so you need to set key as a unique value between items, then I realize that shopAccount should be your id for each item.
The solution code is below.
class ShopsComponent extends Component {
handleRemove = (shopAccount) => {
this.props.removeShop(shopAccount);
}
render() {
return (
<React.Fragment>
<Header />
{this.props.items.map((shopItem) => <ShopItemComponent key={shopItem.shopAccount} item={shopItem} removeShop={this.handleRemove} />)}
</React.Fragment>
);
}
}
I hope you can find useful.
Note, when you are using a arrow function into your class, don't bind that method into the constructor, so remove it, because
handleRemove = (shopAccount) => {
this.props.removeShop(shopAccount);
}
is already binded.

ComponentDidUpdate doesn't work

I'm trying to render dynamically a collection of component using componentDidUpdate.
This is my scenario:
var index = 0;
class myComponent extends Component {
constructor(props) {
super(props);
this.state = {
componentList: [<ComponentToRender key={index} id={index} />]
};
this.addPeriodHandler = this.addPeriodHandler.bind(this);
}
componentDidUpdate = () => {
var container = document.getElementById("container");
this.state.componentList.length !== 0
? ReactDOM.render(this.state.componentList, container)
: ReactDOM.unmountComponentAtNode(container);
};
addHandler = () => {
var array = this.state.componentList;
index++;
array.push(<ComponentToRender key={index} id={index} />);
this.setState = {
componentList: array
};
};
render() {
return (
<div id="Wrapper">
<button id="addPeriod" onClick={this.addHandler}>
Add Component
</button>
<div id="container" />
</div>
);
}
}
The problem is that componentDidUpdate work only one time, but it should work every time that component's state change.
Thank you in advance.
This is not how to use react. With ReactDOM.render() you are creating an entirely new component tree. Usually you only do that once to initially render your app. Everything else will be rendered by the render() functions of your components. If you do it with ReactDOM.render() you are basically throwing away everything react has already rendered every time you update your data and recreate it from scratch when in reality you may only need to add a single node somewhere.
Also what you actually store in the component state should be plain data and not components. Then use this data to render your components in the render() function.
Example for a valid use case:
class MyComponent extends Component{
state = {
periods: []
};
handleAddPeriod = () => {
this.setState(oldState => ({
periods: [
...oldState.periods,
{/*new period data here*/}
],
});
};
render() {
return (
<div id="Wrapper">
<button id="addPeriod" onClick={this.handleAddPeriod}>
Add Component
</button>
<div id="container">
{periods.map((period, index) => (
<ComponentToRender id={index} key={index}>
{/* render period data here */}
</ComponentToRender>
))}
</div>
</div>
);
}
}
}
Also you should not work with global variables like you did with index. If you have data that changes during using your application this is an indicator that is should be component state.
try
addHandler = () =>{
var array = this.state.componentList.slice();
index++;
array.push(<ComponentToRender key={index} id={index}/>);
this.setState=({
componentList: array
});
}
if that works, this is an issue with the state holding an Array reference that isn't changing. When you're calling setState even though you've added to the Array, it still sees the same reference because push doesn't create a new Array. You might be able to get by using the same array if you also implement shouldComponentUpdate and check the array length of the new state in there to see if it's changed.

Categories