This is a bit of a vague question but let me try via pseudocode. If I create an array of child objects in a parent object:
class Parent extends React.Component {
constructor() {
this.state = {kids: [<Child/>,<Child/>]};
}
render () {
return <div>{this.state.kids[0]}{this.state.kids[1]}</div>
}
}
class Child extends React.Component {
...
}
If I do a setState on a Child within the Child component does/should that change the parent kids array? My thinking is that the elements of that array are the Children so changing a Child should change the element. Am I wrong in my understanding?
Unless you have a specific callback that happens when the child updates that triggers the parent, then the parent won't get that update.
This is why most React developers have adopted a smart and dumb component pattern: You really shouldn't have the state of the children managed in both components. The parent component should provide callback functions as props to the child components that handle any sort of changes that would apply to that child and then update its own state accordingly, once its state is updated it will pass the necessary parts down to each child component as props.
Your goal should be to have the least amount of state spread across your components and try to keep state managed in one component and the rest just receive props. A great article on this is: http://jaketrent.com/post/smart-dumb-components-react/
Related
I was doing a POC coding on React js with component which has a Child component.As far as I know, there was no other way to update the state of parent from child except through a call back function from the child to the parent component. In my case, I tried to pass the state of the parent to the child and set them on the child state directly as props (this.props.).I noticed that if I change the state of the child, the state of the parent is also getting updated. I'm bit confused. Could somebody please help ?
Here is my code.
index.js
ReactDOM.render(<App2/>,document.getElementById('root'));
App2.js - Parent component
import React from 'react'
import ScreenTest From './ScreenTest'
class App2 extends React.Component{
state={
address : {
houseName:'1234 House Name'
}
}
render(){
return(
<ScreenTest parentState={this.state} address={this.state.address} />
)
}
}
ScreenTest.jsx - Child Component
import React from 'react';
class ScreenTest extends React.Component{
state={
parentState: this.props.parentState,
address : this.props.address
}
clickButton = () =>{
let addressTemp = this.state.address;
addressTemp.city= "Kerala";
this.setState({
address:addressTemp
})
}
render(){
console.log("To view the state when the screen renders",this.state)
return(
<a onClick={this.clickButton}>Click me to update the state and re render </a>
)
}
}
Code explanation:
I am invoking App2 component which has a child Component ScreenTest. I pass the currentState of App2 to ScreenTest. In ScreenTest i set the state from the values passed as props. In ScreenTest I have an anchor tag when clicked, updates the "address" state of ScreenTest and re render Screen. When the screen is re rendered , i check the state to see that parentState is also getting updated with new Address (i.e city is added to it).
Please tell me how the parentState is also getting affected by it. I'm bit confused.
You must note that when docs say that in order to update parent state from child, you must make use of callback and let the parent update its state, its the ideal and the correct way of doing it
In your code you are accidently updating the parent state you mutate the state by calling
let addressTemp = this.state.address;
addressTemp.city= "Kerala";
In Javascript, object are used by reference and updating a property in object directly will update it for anyone using that reference
So when you assign props to state in constructor like below
state={
parentState: this.props.parentState,
address : this.props.address
}
The state properties hold the reference of props object and hence the props also get updated when you mutate the state property by updating addressTemp state
The ideal way to update state is to clone it and then make changes so that you avoid unexpected issues
clickButton = () =>{
let addressTemp = {...this.state.address}; // clone state
addressTemp.city= "Kerala";
this.setState({
address:addressTemp
})
}
Lets say I have component named Vault
class Vault Component{
State : { animal: dog,color:blue}
}
Lets say I have button in component named App with a button
class App Component{
State: { animal:null,color:null}
}
<div onCLick = {goGetVaultData()} className="button">Press Me</div>
Question is how does goGetVaultData function look to extract state from a diffrent component
goGetVaultData(){
// what do I look like ?
}
If you want data from a parent component, have the parent pass it down as a prop, then access it using this.props.
If you want data from a child component, pass a function as a prop to the child. The child calls that function, and when they do you call this.setState to save the value, and access it later using this.state
If you want data from a sibling component, move the state up to whatever component is the common ancestor of the two components. That common ancestor passes props down to both components.
As we know,parent Component can not change child Component state,because state is independent and private! And the Official documents also said "In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input",then why we can use this.setState({value:this.value+1}) in parent Component to change ???I was confused about this!
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 100};
setTimeout(
() => {
this.setState({value:(this.state.value+1)});
},
1000
);
}
render() {
return (
<inpt value={this.state.value} />
//value will change from 100 to 101
//if here is a user-defined component,we must use
//componentWillReceiveProps(nextProps){this.setState({value:nextProps.value})}
// to update child component,but the DOM component doesn`t need!why??
//Does DOM component hasn`t it`s own state?
);
}
}
from the same page, you get the quote, react mentions that the form inputs are a Controlled Components, which means that the parent component of them can affect there state and it can know some information of their current state, as the onChange listener on the input, the parent component will know when the input is changed and what its new state for the value.
the opposite of this is the uncontrolled components which is a component that the parent may not know anything about its current state, as the image slider in a page, the page doesn't know what is the images that the slider renders, and it doesn't know which image is active now, until you add a handler like onImageChange, which will tell the page which image is the active now, and by that you turned it from uncontrolled component to a controlled component.
Recap:
the controlled component: a component that changes its own state, based on parent component props values, and can share some of its state information with the parent component by the callbacks that the parent passes to it as props.
the uncontrolled component: a component that doesn't change its own state, based on the props that passed to it from the parent, and doesn't share pieces of its state with the parent by the callbacks that the parent passes to it as props.
I hope that answered your question.
I am working since more than a year with React and i have read Thinking in react, Lifting state up, and State and lifecycle.
I have learned that React's concept with data flow is is One-way data flow.
Citates from these pages:
React’s one-way data flow (also called one-way binding) keeps everything modular and fast.
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand, so follow these steps to figure it out:...
If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.
As i understand this, following example is not allowed because i am passing child state data to the parent. But i see some developers working like that:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { fromParent: null };
}
addSomething(stateValueFromChild) {
this.setState({fromParent: stateValueFromChild});
}
render() {
return <Child
addSomething={(stateValueFromChild) => this.addSomething(stateValueFromChild)}>
// ...
</Child>;
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.state = { fromChild: 'foo' };
}
render() {
return <Form onSubmit={() => this.props.addSomething(this.state.fromChild)}>
// ...
</Form>;
}
}
My questions now are:
Is this really not allowed?
Why should this not be modular and fast?
Is this really braking the one-way-dataflow, becoming a two way dataflow?
What other problems could happen with this way?
When i would lift the state up, how would you solve following case; 50 concrete parents that uses that child component, should every parent have a same initialized sub-state for the same child that they are using?
Is this really not allowed?
Why should this not be modular and fast?
Excellent questions. This is allowed. It's just a bit tricky to make it work right because you've got state synchronization here. In the modern frontend world, the state synchronization is believed to be a very challenging task.
The problem will appear when you'll need to sync the state in two directions. For instance, if this child form is used to edit some element of the list, and you're changing the current element of the list. You'll need the child component to detect that situation and sync its local state with the new element from props during the particular UI update. As long as you don't have that, you're fine.
Is this really braking the one-way-dataflow, becoming a two way dataflow?
Nah, it's not. It's still unidirectional data flow because React can't work in any other way by design; UI updates always coming from top to bottom. In your example, your child triggers an event which causes the parent to update its state (it's totally fine), which will cause the UI update of the parent and the child. If you really violate "unidirectional data flow", you'll feel it. You will get an infinite loop or something similar.
When i would lift the state up, how would you solve following case; 50 concrete parents that uses that child component, should every parent have a same initialized sub-state for the same child that they are using?
Yep, that's what they mean by "lifting the state". You organize your root state as a tree reflecting the state of the children, then pass down elements of the state to children along with callbacks to modify the root state.
It's allowed and there is nothing wrong with your code, but I would not call it passing state from child to parent. All you do is invoking method passed in props and triggered by event with some argument, which in your example is child's state value, but it could be any other variable. Parent component knows nothing about nature of this argument, it just receives the value and able to do anything with it, for example change it's own state to another. If Child's state will change, Parent is not going to receive this update without onSubmit event fired again. But children always receive updates from the parent and automatically get rerendered, when props get changed. And of course some of the props could be states of some parents. Here is the major difference in behavior.
There is a good article explaining this in details: Props down, Events Up
Your question is absolutely correct, many times developer (including myself) struggled for passing child's components state or props to parent component.
I always do logic for getting next state or next props in child component and pass next state or next props to parent component by using handler functions of parent component.
import React, { Component } from "react";
import { render } from "react-dom";
class Parent extends Component {
constructor(props) {
super(props);
this.handleSomething = this.handleSomething.bind(this); // binding method
this.state = {
fromParent: "foo"
};
}
handleSomething(value) {
this.setState(prevState => {
return {
fromParent: value
};
});
}
render() {
return (
<div>
<h1>State: {this.state.fromParent}</h1>
<Child handleSomething={this.handleSomething} />
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
fromChild: "bar"
};
}
render() {
return (
<div>
<button
onClick={e => {
const { fromChild } = this.state;
// do whatever as per your logic for get value from child pass to handleSomething function
// you can also do same for handling forms
this.props.handleSomething(fromChild);
}}
>
Click Me
</button>
</div>
);
}
}
render(<Parent />, document.getElementById("app"));
Similar to Pass props to parent component in React.js but I am only interested in getting the child component's default props into the parent.
So why would I need to do that?
Well, I have a parent component that renders a child component containing an HTML form. The parent's render() method passes its state data down to the child as props, as it should.
Initially, the child form should contain some default data only. And it makes sense for that data to be taken from the defaultProps defined in the child component. After all, I don't want to be setting up a load of default data in the parent's state for the sole purpose of passing it down to the child as default props. The parent should not need to define the child's default props. The child should know what its own default props are.
So in my initial parent render(), I leave my state as undefined. When this gets passed down to the child as undefined props, the child will use its defaultProps instead. This is just what I want.
Time passes...
Now the user changes a field on a child component's form. I pass that change back up the parent via a callback function for it to recalculates the parent's new state. I then call a setState() in the parent to re-render all the child components as normal.
The problem is that I need my parent's state to be an object, containing further nested objects, and am using the [React Immutability Helpers][1] to calculate the new state in the parent, like so:
handleFormFieldChange(e) {
// reactUpdate imported from 'react-addons-update'
var newState = reactUpdate(this.state, {
formData: {values: {formFieldValues: {[e.currentTarget.name]: {$set: e.currentTarget.value}}}}
});
this.setState(newState);
}
The first time this code runs, it will throw an error because it's attempting to update the state values and there is no state to update. (I left it undefined, remember!)
If I attempt to get around this by setting up a default initial state to an empty object (each with nested empty objects) I run into a catch-22. On the first render, these empty values will get passed down the child as empty props, so overriding the defaultProps that I set up for the child component. Bummer!
So as far as I can see, I need a sensible initial state to pass down to the child component, but without (re)defining the whole thing again in the parent. So in this case, I think it would make sense to pull the child's defaultProps into the parent, just in order to set the parent's initial state.
I have a way of doing this, which I will post later on. But before I do that, does anybody have a better way of doing this? One that would avoid having to pass the defaultProps from the child to the parent at all?
If you're using React.Component then defaultProps is a static object on the class so it's easy to get.
export default class Child extends React.Component {
static defaultProps = { ... }
}
// If you don't have es7 static support you can add it after the class def:
Child.defaultProps = { ... }
The parent just needs to do:
Child.defaultProps
to access it.
As threatened in the original post, here's how I'm getting the child's default props sent up to the parent.
I'm using ES6 Classes and the module pattern, with Webpack and Babel to handle the building and transpiling.
So I have two files, let's call them Parent.jsx and ChildForm.jsx. Here's how ChildForm.jsx might look (NB: not working code!):
class ChildForm extends React.Component {
render() {
var fieldValues= this.props.formData.formFieldValues;
return(
<form>
Field 1: <input type="text"
name="field1"
value={fieldValues.field1}
onChange={this.props.handleFieldChange} />
</form>
);
}
}
export function getDefaultProps() {
return {
formData: {
formFieldValues: {
field1: "Apples",
field2: "Bananas"
}
}
};
}
ChildForm.defaultProps = getDefaultProps();
export default ChildForm;
The trick is to move the setting of defaultProps to a separate function, which is also exported from the ChildForm.jsx. Having done that, you can probably guess what I'm going to do in the Parent.jsx module! Let's take a look:
import reactUpdate from 'react-addons-update';
import ChildForm from "./ChildForm.jsx";
import {getDefaultProps as getChildFormDefaultProps} from "./ChildForm.jsx";
class Parent extends React.Component {
constructor(props) {
super(props);
var formDefaultProps = getChildFormDefaultProps();
this.state = {
formData: formDefaultProps
};
this.handleFormFieldChange.bind(this);
}
handleFormFieldChange(e) {
var newState = reactUpdate(this.state, {
formData: {values: {formFieldValues: {[e.currentTarget.name]: {$set: e.currentTarget.value}}}}
});
this.setState(newState);
}
render() {
return (
<div>
<ChildForm
formData={this.state.formData}
handleFieldChange={this.props.handleFormFieldChange} /}
</div>
);
}
}
I import the getDefaultProps function from the ChildForm.jsx module and then use that to set the default state for ChildForm at the Parent.jsx level. That state is then passed down to ChildForm as props.
Although this works, I can't help feeling that it's rather clunky. Although I'm defining the defaultProps at the ChildForm.jsx level, where they should be, they're never actually used as defaultProps at that level! Rather, they're passed up the Parent, which uses them to set state, which in turn is passed down to ChildForm as real props.
Still, this is preferable to having to define a default state for the ChildForm component all over again in the Parent component. So it will do for now, unless any of you kind people can suggest something cleaner!