How to Reset Child Elements' State

How to reset child elements' state?

That would be a little hard since your Child components are managing their own state.

You can convert them into dumb components and manage their state in your Parent component.

Something like this

const Parent = React.createClass({
getInitialState() {
return {counters: [0,0,0]};
},
handleClick(index){
let newCounterState = this.state.counters.map(() => 0);
newCounterState[index] = this.state.counters[index] + 1 ;
this.setState({counters : newCounterState})
},
render() {
const rows = this.state.counters.map((value,index) => (
<Child
key={index}
handleClick={() => this.handleClick(index)}
counter={value}
/>
))
return (
<ul>
{rows}
</ul>
);
}
});

const Child = ({counter,handleClick}) => (
<div onClick={handleClick}>
{counter}
</div>
)

ReactDOM.render(
<Parent />,
document.getElementById('app')
);

jsfiddle

How do I reset state from a parent component in a child component?

In App.js, pass as props setModalShow to AlertModal like so :

<AlertModal modalOpen={modalShow} modalText={modalMessage} setModalShow={setModalShow}/>

Then in AlertModal.js (notice I simplified the code, for what you want to do, you don't need that state and useEffect) :

const AlertModal = (props) => {

return (
<Modal show={props.modalOpen} onHide={()=> props.setModalShow(false)}>
<Modal.Header closeButton>Alert</Modal.Header>
<Modal.Body>{props.modalText}</Modal.Body>
</Modal>
);
};

export default AlertModal;

How can reset a React child component back to original state after it updates state in the parent

You would want to make your Range component controlled by passing the value to it from the parent and getting rid of the default

import React, { useState } from "react";

export const App = () => {
const [rangeValue, setRangeValue] = useState(0)

const reset = (e) => {
e.preventDefault()
setRangeValue(0)//reset state to 0 in App
//how can I get the initial Position in Range component back to 0?
}

return (
<div>
<p>The range value is: {rangeValue}</p>
{/* pass the value here */}
<Range rangeValue={rangeValue} setRangeValue = {setRangeValue}/>
<p><a href="/#" onClick={reset}>reset</a></p>
</div>
)
}

const Range = ({rangeValue, setRangeValue: setRangeValue}) =>
{
const handleChange = (event) => {
setRangeValue(event.target.value)
}
return (
<input
type="range"
min="0"
max="10"
step="1"
value={rangeValue} // <-- here get the value from parent, when reset it will come down from parent again without whatever value it was reset to
onChange={(event) => {handleChange(event)}} />
)
}

export default App;

How can parent component reset many children in React

The simplest solution is to actually change the key of the common parent of the grid element that forces all the children to remount and this resetting all their states

Sample demo

class Child extends React.Component {   state = {      counter: 0   }   render() {    return (      <div>{this.state.counter}<button onClick={() => this.setState(prev => ({counter: prev.counter+1}))}>Increment</button></div>    )   }}class App extends React.Component{ state = {  elemKey: 0, }  render() {  return (   <React.Fragment>    <div key={this.state.elemKey}>      {[...Array.from(new Array(10))].map((item, index) => {         return <Child key={index} />      })}    </div>    <button onClick={() => {this.setState(prev => ({elemKey: (prev.elemKey + 1)%2}))}}>Reset</button>   </React.Fragment>  ) }}
ReactDOM.render(<App/>, document.getElementById('app'));
<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><div id="app"/>

How to reset state in children class component at the same time with parent component in React Native?

In PlaceInput component, pass props value to parent where you want,

class PlaceInput extends React.Component{

//... your code method
this.props.updateClean("") // pass your value to parent

}

Then in MainMap component,

<PlaceInput
id={itemData}

defaultValue={this.state._userLocationDisplayed}
displayDefaultValue={!index}
doCleanState={this.state.doCleanState}
updateClean={(text)=> setState({doCleanState:text})} // <-- change like this.
/>

How can I change a child's state from the parent component

You can keep all of the state values in the parent component and pass them down as props with a change handler to your presentational components. Then you can just reset the whole state when you submit the form. This is probably the most "react-y" way to do it.

If you don't want to do that, you could pass in a sort of "reset" prop to each of your child components and when this prop turns to true, reset the state, then reset the parent "reset" prop back to false. However, I personally don't think this is a great way to do this and would strongly recommend the first option.

Edit: You definitely don't need to introduce redux to accomplish what you're trying to do

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

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.



Related Topics



Leave a reply



Submit