How to Force Update Child Component from Parent Component in Reactjs

How to do React forceUpdate() to a child component?

If child component is not memoized then rendering its parent will render the child.

If child component is memoized, you could force update with its reference.

And of course, passing different properties to a child, changing its state, will re-render it.

Changing the key will UNMOUNT the component, it is like making a conditional rendering on it.

Here is an example demonstating everything mentioned:

class Child extends React.Component {
componentDidMount() {
console.log("mounted");
}
render() {
console.log("rendered");
return <div>Child</div>;
}
}

class App extends React.Component {
state = {
counter: 0
};

childRef = React.createRef();
onClick = () => this.forceUpdate();
onCounter = () => this.setState({ counter: this.state.counter + 1 });
onRef = () => this.childRef.current.forceUpdate();

render() {
return (
<>
<Child key={this.state.counter} ref={this.childRef} />
<button onClick={this.onClick}>Render</button>
<button onClick={this.onCounter}>Update Key</button>
<button onClick={this.onRef}>Render with ref</button>
</>
);
}
}

Edit lucid-hill-vfvr3

How to force update child component from parent component in reactjs

child always re-renders when parent does..
use this code for your project

Parent.js

import React, { Component } from "react";
import Child from './child'

class Parent extends Component {
constructor(props) {
super(props);
this.state ={
lblName: "Name",
lblGender: "Gender",
lblDOB: "Date Of Birth",
lblNatio: "Nationality",
};
}
ChangeLanguage(lang, e){
if(lang === "en"){
this.setState(
{
lblName: "Name",
lblGender: "Gender",
lblDOB: "Date Of Birth",
lblNatio: "Nationality",
});
}
else if(lang === "sp"){
this.setState(
{
lblName: "Nombre",
lblGender: "Género",
lblDOB: "Fecha de nacimiento",
lblNation: "Nacionalidad",
});
}

}
render() {
return (
<div>
<Child {...this.state} />
<button onClick = {this.ChangeLanguage.bind(this, "en")}>English</button>
<button onClick = {this.ChangeLanguage.bind(this, "sp")}>Spanish</button>
</div>
)}
}

export default Parent

Child.js

import React, { Component } from "react";

class Child extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div>
<label>{this.props.lblName}</label>
<input type="Text"></input>
</div>
<div>
<label>{this.props.lblGender}</label>
<input type="Text"></input>
</div>
<div>
<label>{this.props.lblDOB}</label>
<input type="Date"></input>
</div>
<div>
<label>{this.props.lblNation}</label>
<input type="Text"></input>
</div>
</div>
)}
}

export default Child

Sample index.js file

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Parent from './parent'

class App extends Component {
render() {
return (
<div className="App">
<Parent />
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('root'))

for now all the files are in the src folder

How do I force parent component re render from child component

This is an example of what a Context that wrapped a Playlist object could look like.

Here we have 2 components, PlaylistDetails and AddSongForm, and a single Context, PlaylistContext. Our PlaylistProvider wraps the PlaylistContext and exposes both the playlist state (the list of songs) and a function to update that state. The PlaylistDetails and AddSongForm components read the playlist state from the PlaylistProvider so whenever that is updated they re-render automatically.

import { createContext, useContext, useState } from "react";

const PlaylistContext = createContext(null);

const PlaylistProvider = ({ children }) => {
const [playlist, setPlaylist] = useState([]);

const updatePlaylist = (songName) => {
setPlaylist((prevPlaylist) => [...prevPlaylist, songName]);
};

return (
<PlaylistContext.Provider value={{ playlist, updatePlaylist }}>
{children}
</PlaylistContext.Provider>
);
};

const PlaylistDetails = () => {
const { playlist } = useContext(PlaylistContext);

if (playlist.length === 0) {
return null;
}

return (
<>
<h1>Songs:</h1>
<ul>
{playlist.map((song) => (
<li key={song}>{song}</li>
))}
</ul>
</>
);
};

const AddSongForm = () => {
const { updatePlaylist } = useContext(PlaylistContext);
const [songName, setSongName] = useState(null);

return (
<form
onSubmit={(e) => {
updatePlaylist(songName);
e.preventDefault();
}}
>
<label>
Song Name:
<input type="text" onChange={(e) => setSongName(e.target.value)} />
</label>
<button type="submit">Add Song</button>
</form>
);
};

export default function App() {
return (
<PlaylistProvider>
<PlaylistDetails />

<AddSongForm />
</PlaylistProvider>
);
}

How can i refresh my child componet by using a button click on parent componet?

Changing state should re-render the current component and all the child components inside it.

I ran your code and there is a mistake with how you defined the setState method. You need to use arrow function, otherwise this will be undefined.

So change your submit button like following and it should work.

submit = () => {
this.setState({ isRefreshClicked: true });
};

Here's the stackblitz: https://stackblitz.com/edit/react-f5q3n8?file=src/MyComponent.js

How to re-render parent component from child component

You have to have state in the parent component and pass down this state to the child component:

import React, { Component } from "react";
import Child from "./Child";

class Parent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
rerender = () => {
this.forceUpdate();
};
forceUpdate = () => {
this.setState((state) => ({
counter: state.counter + 1
}));
};
render() {
console.log("got rendered");
return (
<div>
<p className="animate-left" key={this.state.counter}>Animation</p>
<Child rerender={this.rerender} />
</div>
);
}
}

export default Parent;

React JS: State Changes on Child component updating the Parent Component

From gif it seems to me like whole page is reloading, but I'm not sure what is inside MediumButton component. By default button inside form element will submit the form on click, you need to implement preventDefault in your button onClick handler, here is an example how to do it:

function App() {
const handleClick = (e) => {
e.preventDefault();
}
return (
<div className="App">

<form>
<p>This is simple form</p>
<button onClick={(e) => handleClick(e)}>hello</button>
</form>
</div>
)
};


Related Topics



Leave a reply



Submit