Handle child component update (controlled vs uncontrolled) - javascript

There is a Parent component which container a Child component.
Parent supposed to load the data (e.g. using AJAX) and update the Child inputs.
Child supposed to listen for the changes to its inputs and update them as well.
Setting Child props from Parent sets inputs values:
<input value={this.props.someVal}
But this makes it unable to self-update the child, since in order to self-update its inputs it has to use:
<input value={this.state.someVal}
Does this mean, Child has to listen for input change and triggers Parents handler-function that will sets its props?
I thought that setting components props - auto-updates corresponding state (triggering re-render) and that using <input value={this.state.someVal} should cover both cases.

There really isn't any connection between props and state. These are two different mechanisms: state is internal to the component and used for keeping encapsulated data. Props are sent by an enclosing object, as you've done.
There are several ways to go about this, but the general consensus is that having state in one place and passing it down the component tree leads to less messy code and bugs. That means your statement is correct - you'll have to pass update functions to the child component from the parent, so that when invoked it will re-render the child with new props.

I have found the way to do it. Smth like (TypeScript syntax):
componentWillReceiveProps(props: Props) {
this.setState({
data: props.data
})
}
This will allow to update the child both from the parent and child itself. Not sure whether this is a right approach, but it kinda works.

Parent component will make the ajax call and set its own state, the state values will be passed as props, which will update the child always.
class parent extends React.Component {
state = {
value: null
}
componentWillMount() {
this.makeApiCall()
}
makeApiCall = () => {
fetch("api_ulr")
.then(() => {
this.setState({
value: newValue,
})
})
}
render() {
return ( < Child value = {
this.state.value
} > < /Child>)
}
}
now child will update whenver a new data comes.

Related

How does React re-use child components / keep the state of child components when re-rendering the parent component?

In React, every time a component is rendered/re-rendered, it regenerates all of it's child nodes/components using createElement. How does React know when to persist the components state between re-renders?
As an example, consider the following code:
class Timer extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(state => ({ seconds: state.seconds + 1 }));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return createElement('div', null,
'Seconds: ',
this.state.seconds
);
}
}
class Button extends Component {
constructor(props) {
super(props);
this.state = { clicks: 0 };
}
click() {
this.setState(state => ({ clicks: state.clicks + 1 }));
}
render() {
return createElement('button', { onClick: () => this.click() },
createElement(Timer, null),
'Clicks: ',
this.state.clicks
);
}
}
render(createElement(Button, null), document.getElementById('root'));
You can try this code with the Preact REPL here.
Notice that when the button is pressed and the clicks value is updated, the state of the Timer component persists and is not replaced. How does React know to re-use the component instance?
While this may seem like a simple question at first, it becomes more complex when you consider stuff like changing the props passed to a child component or lists of child components. How does React handle changing the props of a child component? Does the child component's state persist even though it's props have changed? (In Vue, the state of a component does persist when it's props change) How about lists? What happens when an entry in the middle of a list of child components is removed? A change to a list like that would obviously generate very different VDOM nodes, yet the state of the components still persists.
createElement vs render vs mount
When a React Component such as your Button is rendered, a number of children are created with createElement. createElement(Timer, props, children) does not create an instance of the Timer component, or even render it, it only creates a "React element" which represents the fact that the component should be rendered.
When your Button is rendered, react will reconcile the result with the previous result, to decide what needs to be done with each child element:
If the element is not matched to one in the previous result, then a component instance is created then mounted then rendered (recursively applying this same process). Note that when Button is rendered for the first time, all of the children will be new (because there is no previous result to match against).
If the element is matched to one in the previous result, then the component instance is reused: its props are updated, then the component is re-rendered (again, recursively applying this same process). If the props did not change, React might even choose not to re-render as an efficiency.
Any elements in the previous result that was not matched to an element in the new result will be unmounted and destroyed.
React's diffing algorithm
An element "matches" another one if React compares them and they have the same type.
The default way for React to compare children, is to simply iterate over both lists of children at the same time, comparing the first elements with each other, then the second, etc.
If the children have keys, then each child in the new list is compared to the child in the old list that has the same key.
See the React Reconciliation Docs for a more detailed explanation.
Examples
Your Button always returns exactly one element: a button. So, when your Button re-renders, the button matches, and its DOM element is re-used, then the children of the button are compared.
The first child is always a Timer, so the type matches and the component instance is reused. The Timer props did not change, so React might re-render it (calling render on the instance with the same state), or it might not re-render it, leaving that part of the tree untouched. Both of these cases would result in the same result in your case - because you have no side-effects in render - and React deliberately leaves the decision of when to re-render as an implementation detail.
The second child is always the string "Clicks: " so react leaves that DOM element alone too.
If this.state.click has changed since the last render, then the third child will be a different string, maybe changing from "0" to "1", so the text node will be replaced in the DOM.
If Buttons render were to return a root element of a different type like so:
render() {
return createElement(this.state.clicks % 2 ? 'button' : 'a', { onClick: () => this.click() },
createElement(Timer, null),
'Clicks: ',
this.state.clicks
);
}
then in the first step, the a would be compared to the button and because they are different types, the old element and all of its children would be removed from the DOM, unmounted, and destroyed. Then the new element would be created with no previous render result, and so a new Timer instance would be created with fresh state, and the timer would be back at 0.
Timer matches?
previous tree
new tree
no match
<div><Timer /></div>
<span><Timer /></span>
match
<div>a <Timer /> a</div>
<div>b <Timer /> b</div>
no match
<div><Timer /></div>
<div>first <Timer /></div>
match
<div>{false}<Timer /></div>
<div>first <Timer /></div>
match
<div><Timer key="t" /></div>
<div>first <Timer key="t" /></div>
Never used Vue, but this is my take.
Does the child component's state persist even though it's props have changed? (In Vue, the state of a component does persist when it's props change)
This depends on how you handle the props in your child.
This child will re-render every time you change (mutate) your props.
const Child = (props) => {
return <div>{ props.username }</div>;
};
This child will not re-render when props change since the return value is dependent on the local state, and not the props.
const Child = (props) => {
const [state, setState] = useState(props.username);
return <div>{ state }</div>;
};
This child will re-render when props change, as local state updates with the new props.
const Child = (props) => {
const [state, setState] = useState(props.username);
useEffect(() => {
// changing props changes the component's state, causing a re-render
setState(props.username);
}, [props]);
return <div>{ state }</div>;
};
As seen in the examples above, the programmer is the one in control of whether React triggers a re-render of a child.
How about lists? What happens when an entry in the middle of a list of child components is removed? A change to a list like that would obviously generate very different VDOM nodes, yet the state of the components still persists.
When a list of children is involved (eg. when .map is used) React will require the key parameter, so that React will be aware what was add/removed/changed between parent component re-renders.
React requires that the same key be used for the same components to prevent unnecessary re-renders (don't use Math.random() as your key).

What is the best approach in React Application for the case without using Redux?

I want to submit data via an api on a click of button in the parent Component, on collecting data from multiple sub components in different hierarchy.
I have a discussion on the case with one of my colleague and he suggest me to have a method in a parent comp. and share that (as a handler) to child(s) in prop and then to further to its child(s), keeping child comp. as stateless comp. Such that when user inputs the data it will store into a state variable (in parent comp.) via that handler method. For e.g:
class Parent extends Component {
constructor(props){
this.state.data = {}
}
updateHndler(key, value){
this.setState({
data : {...this.setState.data, key: value}
})
}
}
const ChildA = props => {
onComplete(e){
this.props.updateHndler('text', e.target.value)
}
return (<div>
...
..
<input .. onChange={()=>{onComplete(e)}}
</div>)
}
As each sub-component setting the value in parent state variable for each value it is getting update and its render() method keeps trigger, considering the rendering cost for all the sub-components on each change is the above approach is even good enough?
Thanks

React.js: Changing the child state also changes its proptype passed by parent

The issue I'm having is that when I change the state of the child component, the state of the parent component is also changed. I'm passing the prop to the child as so:
{this.state.users.map((user, index) => (
<UserRow
key={user.id}
user={user}
removeUser={this.removeUser}
getUserInfo={this.getUserInfo}
finishFunc={this.finishChanges}
/>
))}
And then assigning that prop to the a state of the child like this:
state = {rowUser: this.props.user};
However, when I update this child state, it seems that the parent state updates without re-rendering.
I'm displaying the information through the prop, not the state
<div>{this.props.user.rules.length !== 0 ? this.props.user.rules.length : null}</div>
You can see the initial display here
When I click on the "Add" or "Remove" buttons, the state and display changes. You can see the change in the image here
I'm confused on how changing the child's state updates the parent's state without me specifically passing the data back to the parent. I also don't see how it is changing the display since I'm using the prop, not the state.
You can see all of my code in a sandbox here. You can see the permissions number change whenever you click the "add new permission" and "remove permission" buttons, which I don't want to happen.
How can I avoid having the parent state automatically change when I change the child state?
The Problem:
The issue lied in how I was changing the child's state state = {rowUser: this.props.user}. I was mutating the data and resetting the state like this:
addPermission = () => {
const tempUser = { ...this.state.rowUser };
tempUser.permissions.push({
property: "select permission",
info: "type info..."
});
this.setState({ rowUser: tempUser });
console.log("[UserEditingRow.js] permission added");
};
The Solution:
Changing the data directly (i.e. tempUser.permissions.push({...});) was causing a problem. I used React immutability helper to help update the child's state more specifically. So, the new function would be:
addPermission = () => {
this.setState(
update(this.state, {
rowUser: {
permissions: {
$push: [{property: 'select rule', info: ''}],
},
},
}),
);
console.log('[UserEditingRow.js] rule added');
};
Setting the state with immutability helper allowed the child component's state to change without updating the parent component's state and solved my problem.
After reviewing your Sandbox, the issue is you are assigning props.user to state.rowUser and is creating a pointer to the parent components value. This means whenever you change this.state.rowUser it will actually be updating the reference to props.user.
Solution
Use the constructor() to bind the props.user to state.rowUser, this is the recommend approach, additionally use the spread operator to create a new instance of the object passed into the component, this will ensure no pointer is created.
https://reactjs.org/docs/react-component.html#constructor
constructor(props){
this.state = { rowUser: ...props.user }
}
Additionally
Looking quickly at the sandbox I also found a few other anti-patterns that will be causing you some issues.
You are updating state directly Line 76 to 84 in UserRow then calling setState, what you should be doing is using the spread operator to clone the object const tempUserRow = { ...this.state.userRow } then manipulating the object and set it in state via setState. This will ensure your shallow compare in shouldComponentUpdate passes and re-renders your component.
You are using shouldComponentUpdate which is good, but your not doing anything that React.PureComponent does for you out of the box, so you should change extends React.Component to be extends React.PureComponent
https://reactjs.org/docs/react-api.html#reactpurecomponent

React Native - Modify a prop within the same component

I have simple questions:
Is it possible to modify a prop (not state) within a React Native component (not from parent component)?
Following [1], if I want to modify a prop within the same component, how can I achieve that (or workarounds if answer in [1] is No)?
If I have the following:
//Parent
render(){
return <View><ChildComponent propA={this.state.propA} /></View>
}
triggerChangeInParent(val) {
this.setState({
propA: val
});
}
//Child (ChildComponent)
render() {
return <View><Text>{this.props.propA}</Text></View>
}
triggerChangeInChild(val) {
//To set props.propA here
}
Both parent and child components are allowed to modify "propA". Whoever triggers the latest will have its value taken precedence for modifying "propA" (eg if "triggerChangeInChild" is triggered after "triggerChangeInParent", then "val" from "triggerChangeInChild" will be used for "propA".
My question is, how do we achieve that (what possible solutions/alternatives to solve this problem)? What is the best practice/pattern?
Thanks!
State is mutable and props is immutable, so you can't modify the props within component. Please do it outside the current component. If you're using redux, you can do it in a reducer.
You should modify the propA on parent only, please write a method in parent, then pass it to child via prop. So you can call the method from child, mean that you make the change inside child.
Parent
contractor(props){
super(props)
this.modifyPropsOnParent = this.modifyPropsOnParent.bind(this)
}
modifyPropsOnParent(){
// do your change here
}
render() {
return <Child modifyPropsOnParent={this.modifyPropsOnParent} otherProp={yourProps} />
}
Child can call the parent method by this.props. modifyPropsOnParent()

What is the difference between state and props in React?

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says
Both props and state changes trigger a render update.
Later in the article it says:
Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.
So props can change but they should be immutable?
When should you use props and when should you use state?
If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?
Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you're using JSX, the more familiar tag attributes.
<MyChild name={this.state.childsName} />
The parent's state value of childsName becomes the child's this.props.name. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:
this.setState({ childsName: 'New name' });
and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.
<MyChild name={this.state.childsName} onNameChanged={this.handleName} />
The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.
handleName: function(newName) {
this.setState({ childsName: newName });
}
For parent-child communication, simply pass props.
Use state to store the data your current page needs in your controller-view.
Use props to pass data & event handlers down to your child components.
These lists should help guide you when working with data in your components.
Props
are immutable
which lets React do fast reference checks
are used to pass data down from your view-controller
your top level component
have better performance
use this to pass data to child components
State
should be managed in your view-controller
your top level component
is mutable
has worse performance
should not be accessed from child components
pass it down with props instead
For communication between two components that don't have a
parent-child relationship, you can set up your own global event
system. Subscribe to events in componentDidMount(), unsubscribe in
componentWillUnmount(), and call setState() when you receive an event.
Flux pattern is one of the possible ways to arrange this.
- https://facebook.github.io/react/tips/communicate-between-components.html
What Components Should Have State?
Most of your components should simply take some data from props and
render it. However, sometimes you need to respond to user input, a
server request or the passage of time. For this you use state.
Try to keep as many of your components as possible stateless. By doing
this you'll isolate the state to its most logical place and minimize
redundancy, making it easier to reason about your application.
A common pattern is to create several stateless components that just
render data, and have a stateful component above them in the hierarchy
that passes its state to its children via props. The stateful
component encapsulates all of the interaction logic, while the
stateless components take care of rendering data in a declarative way.
- https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state
What Should Go in State?
State should contain data that a component's event handlers may change
to trigger a UI update. In real apps this data tends to be very small
and JSON-serializable. When building a stateful component, think about
the minimal possible representation of its state, and only store those
properties in this.state. Inside of render() simply compute any other
information you need based on this state. You'll find that thinking
about and writing applications in this way tends to lead to the most
correct application, since adding redundant or computed values to
state means that you need to explicitly keep them in sync rather than
rely on React computing them for you.
- https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state
You can understand it best by relating it to Plain
JS functions.
Simply put,
State is the local state of the component which cannot be accessed and modified outside of the component. It's equivalent to local variables in a function.
Plain JS Function
const DummyFunction = () => {
let name = 'Manoj';
console.log(`Hey ${name}`)
}
React Component
class DummyComponent extends React.Component {
state = {
name: 'Manoj'
}
render() {
return <div>Hello {this.state.name}</div>;
}
Props, on the other hand, make components reusable by giving components the ability to receive data from their parent component in the form of props. They are equivalent to function parameters.
Plain JS Function
const DummyFunction = (name) => {
console.log(`Hey ${name}`)
}
// when using the function
DummyFunction('Manoj');
DummyFunction('Ajay');
React Component
class DummyComponent extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />
Credits: Manoj Singh Negi
Article Link: React State vs Props explained
The props vs state summary I like best is here: react-guide Big hat tip to those guys. Below is an edited version of that page:
props vs state
tl;dr If a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.
props
Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.
state
The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.
Changing props and state
props state
Can get initial value from parent Component? Yes Yes
Can be changed by parent Component? Yes No
Can set default values inside Component?* Yes Yes
Can change inside Component? No Yes
Can set initial value for child Components? Yes Yes
Can change in child Components? Yes No
Note that both props and state initial values received from parents override default values defined inside a Component.
Should this Component have state?
State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.
Component types
Stateless Component Only props, no state. There's not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.
Stateful Component Both props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.
sources
Question about 'props' and 'state' - Google Groups
Thinking in React: Identify where your state should live
The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component.
function A(props) {
return <h1>{props.message}</h1>
}
render(<A message=”hello” />,document.getElementById(“root”));
class A extends React.Component{
constructor(props) {
super(props)
this.state={data:"Sample Data"}
}
render() {
return(<h2>Class State data: {this.state.data}</h2>)
}
}
render(<A />, document.getElementById("root"));
State can be changed (Mutable)
Whereas Props can't (Immutable)
props (short for “properties”) and state are both plain JavaScript
objects. While both hold information that influences the output of
render, they are different in one important way: props get passed to
the component (similar to function parameters) whereas state is
managed within the component (similar to variables declared within a
function).
So simply state is limited to your current component but props can be pass to any component you wish... You can pass the state of the current component as prop to other components...
Also in React, we have stateless components which only have props and not internal state...
The example below showing how they work in your app:
Parent (state-full component):
class SuperClock extends React.Component {
constructor(props) {
super(props);
this.state = {name: "Alireza", date: new Date().toLocaleTimeString()};
}
render() {
return (
<div>
<Clock name={this.state.name} date={this.state.date} />
</div>
);
}
}
Child (state-less component):
const Clock = ({name}, {date}) => (
<div>
<h1>{`Hi ${name}`}.</h1>
<h2>{`It is ${date}`}.</h2>
</div>
);
Basically, the difference is that state is something like attributes in OOP : it's something local to a class (component), used to better describe it. Props are like parameters - they are passed to a component from the caller of a component (the parent) : as if you called a function with certain parameters.
Both state and props in react are used to control data into a component, generally props are set by parent and passed to child components and they are fixed throughout the component. For data that is going to change, we have to use state. And props are immutable while states are mutable, if you want to change props you can do from parent component and then pass it to child components.
as I learned while working with react.
props are used by a component to get data from external environment i.e another component ( pure, functional or class) or a general class or javascript/typescript code
states are used to manage the internal environment of a component means the data changes inside the component
Props : Props is nothing but property of component and react component is nothing but a javascript function.
class Welcome extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
const element = ;
here <Welcome name="Sara" /> passing a object {name : 'Sara'} as props of Welcome component. To pass data from one parent component to child component we use props.
Props is immutable. During a component’s life cycle props should not change (consider them immutable).
State: state is accessible only within Component. To keep track of data within component we use state. we can change state by setState. If we need to pass state to child we have to pass it as props.
class Button extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
}
State:
states are mutable.
states are associated with the individual components can't be used by other components.
states are initialize on component mount.
states are used for rendering dynamic changes within component.
props:
props are immutable.
you can pass props between components.
props are mostly used to communicate between components.You can pass from parent to child directly. For passing from child to parent
you need use concept of lifting up states.
class Parent extends React.Component{
render()
{
return(
<div>
<Child name = {"ron"}/>
</div>
);
}
}
class Child extends React.Component{
{
render(){
return(
<div>
{this.props.name}
</div>
);
}
}
state - It is a special mutable property that hold a Component data. it has default value when Componet mounts.
props - It is a special property which is immutable by nature and used in case of pass by value from parent to child. props are just a communation channel between Components, always moving from top (parent) to buttom(child).
below are complete example of combinding the state & props :-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>state&props example</title>
<script src="https://unpkg.com/react#0.14.8/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom#0.14.8/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
var TodoList = React.createClass({
render(){
return <div className='tacos-list'>
{
this.props.list.map( ( todo, index ) => {
return <p key={ `taco-${ index }` }>{ todo }</p>;
})}
</div>;
}
});
var Todo = React.createClass({
getInitialState(){
return {
list : [ 'Banana', 'Apple', 'Beans' ]
}
},
handleReverse(){
this.setState({list : this.state.list.reverse()});
},
render(){
return <div className='parent-component'>
<h3 onClick={this.handleReverse}>List of todo:</h3>
<TodoList list={ this.state.list } />
</div>;
}
});
ReactDOM.render(
<Todo/>,
document.getElementById('root')
);
</script>
</body>
</html>
Props: represents "read-only" data, that are immutable and refer to attributes from parents component.
State: represents mutable data, that ultimately affects what is rendered on the page and managed by internally by the component itself and change overtime commonly due to User input.
Props
props use to pass data in the child component
props change a value outside a component(child component)
State
state use inside a class component
state change a value inside a component
If you render the page, you call setState to update DOM(update page
value)
State has an important role in react
Basically, props and state are two ways the component can know what and how to render. Which part of the application state belongs to state and which to some top-level store, is more related to your app design, than to how React works. The simplest way to decide, IMO, is to think, whether this particular piece of data is useful for application as a whole, or it's some local information. Also, it's important to not duplicate state, so if some piece of data can be calculated from props - it should calculated from props.
For example, let's say you have some dropdown control (which wraps standart HTML select for custom styling), which can a) select some value from list, and b) be opened or closed (i.e., the options list displayed or hidden).
Now, let's say your app displays a list of items of some sort and your dropdown controls filter for list entries. Then, it would be best to pass active filter value as a prop, and keep opened/closed state local. Also, to make it functional, you would pass an onChange handler from parent component, which would be called inside dropdown element and send updated information (new selected filter) to the store immediately. On the other hand, opened/closed state can be kept inside dropdown component, because the rest of the application doesn't really care if the control is opened, until user actually changes it value.
The following code is not completely working, it needs css and handling dropdown click/blur/change events, but I wanted to keep example minimal. Hope it helps to understand the difference.
const _store = {
items: [
{ id: 1, label: 'One' },
{ id: 2, label: 'Two' },
{ id: 3, label: 'Three', new: true },
{ id: 4, label: 'Four', new: true },
{ id: 5, label: 'Five', important: true },
{ id: 6, label: 'Six' },
{ id: 7, label: 'Seven', important: true },
],
activeFilter: 'important',
possibleFilters: [
{ key: 'all', label: 'All' },
{ key: 'new', label: 'New' },
{ key: 'important', label: 'Important' }
]
}
function getFilteredItems(items, filter) {
switch (filter) {
case 'all':
return items;
case 'new':
return items.filter(function(item) { return Boolean(item.new); });
case 'important':
return items.filter(function(item) { return Boolean(item.important); });
default:
return items;
}
}
const App = React.createClass({
render: function() {
return (
<div>
My list:
<ItemList items={this.props.listItems} />
<div>
<Dropdown
onFilterChange={function(e) {
_store.activeFilter = e.currentTarget.value;
console.log(_store); // in real life, some action would be dispatched here
}}
filterOptions={this.props.filterOptions}
value={this.props.activeFilter}
/>
</div>
</div>
);
}
});
const ItemList = React.createClass({
render: function() {
return (
<div>
{this.props.items.map(function(item) {
return <div key={item.id}>{item.id}: {item.label}</div>;
})}
</div>
);
}
});
const Dropdown = React.createClass({
getInitialState: function() {
return {
isOpen: false
};
},
render: function() {
return (
<div>
<select
className="hidden-select"
onChange={this.props.onFilterChange}
value={this.props.value}>
{this.props.filterOptions.map(function(option) {
return <option value={option.key} key={option.key}>{option.label}</option>
})}
</select>
<div className={'custom-select' + (this.state.isOpen ? ' open' : '')} onClick={this.onClick}>
<div className="selected-value">{this.props.activeFilter}</div>
{this.props.filterOptions.map(function(option) {
return <div data-value={option.key} key={option.key}>{option.label}</div>
})}
</div>
</div>
);
},
onClick: function(e) {
this.setState({
isOpen: !this.state.isOpen
});
}
});
ReactDOM.render(
<App
listItems={getFilteredItems(_store.items, _store.activeFilter)}
filterOptions={_store.possibleFilters}
activeFilter={_store.activeFilter}
/>,
document.getElementById('root')
);
State is the way react deals with the information held by your component.
Let's suppose you have a component which need to fetch some data from the server. You usually would want to inform the user if the request is processing, if it has failed, etc. This is a piece of information which is just relevant for that specific component. This is where state enters the game.
Usually the best way to define state is as follows:
class MyComponent extends React.Component {
constructor() {
super();
this.state = { key1: value1, key2: value2 }
}
}
but in the latests implementations of react native you can just do:
class MyComponent extends React.Component {
state = { key1: value1, key2: value2 }
}
These two examples execute in the exact same way, it's just a syntax improvement.
So, what is different from just using object attributes as we always have in OO programming? Usually, the information held in your state is not meant to be static, it will change over time and your View will need to update in order to reflect this changes. State offers this functionality in a simple way.
State IS MEANT TO BE INMUTABLE! and I cannot make enough stress on this. What does this means? It means that you should NEVER do something like this.
state.key2 = newValue;
The proper way of doing it is:
this.setState({ key2: newValue });
Using this.setState your component runs through the update cycle and if any part of the state changes, your Component render method will be called again to reflect this changes.
Check the react docs for an even more expanded explanation:
https://facebook.github.io/react/docs/state-and-lifecycle.html
Props simply are shorthand for properties. Props are how components talk to each other. If you’re at all familiar with React then you should know that props flow downwards from the parent component.
There is also the case that you can have default props so that props are set even if a parent component doesn’t pass props down.
This is why people refer to React as having uni-directional data flow. This takes a bit of getting your head around and I’ll probably blog on this later, but for now just remember: data flows from parent to child. Props are immutable (fancy word for it not changing)
So we’re happy. Components receive data from the parent. All sorted, right?
Well, not quite. What happens when a component receives data from someone other than the parent? What if the user inputs data directly to the component?
Well, this is why we have state.
STATE
Props shouldn’t change, so state steps up. Normally components don’t have state and so are referred to as stateless. A component using state is known as stateful. Feel free to drop that little tidbit at parties and watch people edge away from you.
So state is used so that a component can keep track of information in between any renders that it does. When you setState it updates the state object and then re-renders the component. This is super cool because that means React takes care of the hard work and is blazingly fast.
As a little example of state, here is a snippet from a search bar (worth checking out this course if you want to learn more about React)
Class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)} />
</div>
);
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
}
SUMMARY
Props and State do similar things but are used in different ways. The majority of your components will probably be stateless.
Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed.
State is used for mutable data, or data that will change. This is particularly useful for user input. Think search bars for example. The user will type in data and this will update what they see.
In short.
props values can't be changed [immutable]
state values can be changed, using setState method [mutable]
In general, state of one component(parent) is prop for the child component.
State resides within a component where as props are passed from parent to
child.
Props are generally immutable.
class Parent extends React.Component {
constructor() {
super();
this.state = {
name : "John",
}
}
render() {
return (
<Child name={this.state.name}>
)
}
}
class Child extends React.Component {
constructor() {
super();
}
render() {
return(
{this.props.name}
)
}
}
In the above code, we have a parent class(Parent) which has name as its state which is passed to the child component(Child class) as a prop and the child component renders it using {this.props.name}
In React the states store the data as well as the props. Its difference with the latter is that the stored data can be modified by different changes. These are nothing more than objects written in flat JavaScript, so they can contain data or codes, represent the information you want to model. If you need more details it is recommended that you see these publications
Use of the State in React and
Use of Props in React
The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component.
In answer to the initial question about props being immutable, they are said to be immutable as far as the child component is concerned but are of course changeable in the parent that is passing these props down.
A change in these in the parent will trigger a re-render of the child component with the updated props.
This is my current point of view regarding the explanation between state and props
State is like your local variable inside your component. You can manipulate
the value of state by using set state. You can then pass the value of state
to your child component for example.
Props is the value that exactly located inside your redux store, this actually
comes from state that's originated from reducer. Your component
should be connected to redux to get the value from props. You can also pass
your props value to your child component
You have some data that is being entered by users somewhere in the application.
the component in which the data is being entered should have this data in its state because it needs to manipulate and change it during data entry
anywhere else in the application the data should be passed down as props to all the other components
So yes the props are changing but they are changed at the 'source' and will then simply flow down from there. So props are immutable in the context of the component receiving them.
E.g. a reference data screen where users edit a list of suppliers would manage this in state, which would then have an action cause the updated data to be saved in ReferenceDataState which could be one level below AppState and then this supplier list would be passed as props to all the components that needed to use it.
Some differences between “state” and “props” in react.
React controls and renders DOM based on state. There are two types of component states: props is the state that transfers between components, and state is internal state of components. Props is used for data transfer from the parent component to the child component. The components also have their own state inside: state which can only be modified inside the component.
Generally the state of certain component could be the props of the child component ,props will be passed to children which is stated inside the rendering method of the parent component
From: Andrea Chiarelli book “Beginning React: Simplify your frontend development workflow and enhance the user experience of your applications with React” :
Every React component has a props property. The purpose of this property is to collect data input passed to the component itself. JSX attribute is attached to a React element, a property with the same name is attached to the props object. So, we can access the passed data by using the attached property. In addition, the immutability of props allows us to think of components as pure functions, which are functions that have no side effects (since they don't change their input data). We can think of data passing from one component to another as a unidirectional data flow, from the parent component toward the child components. This gives us a more controllable system.
React provides a mechanism to support the automatic rendering of a component when data changes. Such a mechanism is based on the concept of state. React state is a property that represents data that changes over time. Every component supports the state property, but it should be used carefully. Components that store data that can change over time are said to be stateful components. A stateful component stores the state in the this.state property. To inform a component that the state has changed, you must use the setState() method. State initialization is the only case where you can assign a value to the this.state property without using setState().
setState() merges new data with old data already contained in the state, and overwrites the previous state
setState() triggers the execution of the render() method, so you should never call render() explicitly
State is a special variable in react and is used to re-render component whenever it updates
State is private to the component itself. I.e, it cannot be accessed or modified outside of component. setState/hook used to update state. Whenever state update, component re renders
State is mutable
Props are inputs to component and render content using props data
Props are immutable(Object.Frozen= true)
we can change states value but we can not change props value , or we can say props is immutable and states is mutable
I want to explain state and props in a simple way to you:
state
we use states to store some data. it's also like a variable that when you change it, your component will render again.
to use states you need to import useState hook:
import { useState } from 'react';
const [state_name,function_name] = useState(initial_value);
you can access your state by state_name and you can change it and set a new value to it by function_name.
more info: https://reactjs.org/docs/state-and-lifecycle.html
props
It is a mechanism to send data from one component to other. it also looks like properties in CSS. for example:
<Component props_value={custom_function} />
you can send a custom function to Component and receive it to be manipulate.
more info: https://reactjs.org/docs/components-and-props.html
React Components use state to READ/WRITE the internal variables that can be changed/mutated by for example:
this.setState({name: 'Lila'})
React props is special object that allow programmer to get variables and methods from Parent Component into Child Component.
It's something like a Windows and doors of the house. Props are also immutable Child Component can not change/update them.
There are couple of the methods that help to listen when props are changed by Parent Component.

Categories

Resources