React how to update another component's state? - javascript

I am pretty new to react, trying to make some components work. I have
ObjectA:React.createClass({
propTypes: {
...
},
getInitialState: function() {
return {
myState: null
}
},
updateMyState: function(value) {
this.setState({
myState: value
})
}
render: function() {
return (<div className="my-class">'hello' +{this.state.myState}</div>);
}
});
ObjectB:React.createClass({
propTypes: {
...
},
render: function() {
return (<div className="my-class"><ObjectA / >
</div>);
}
});
I'd like to update ObjectA's state from ObjectB. How could I in ObjectB call ObjectA's updateMyState method?
Thanks!

The basic idea of React is the unidirectional data flow. That means that data is only shared downwards from an ancestor component to its children via the child's properties. We leave Flux like architectures and event emitters out of the equation for this simple example as it's not necessary at all.
The ONLY way then to change a component's state from the outside is changing the props it receives in the parent's render method. so myState would actually live in ObjectB and be given to ObjectA as property. In your example that would look like this:
ObjectA:React.createClass({
propTypes: {
...
},
render: function() {
return (<div className="my-class">'hello' +{ this.props.name }</div>);
}
});
ObjectB:React.createClass({
propTypes: {
...
},
getInitialState: function() {
return {
name: null
}
},
onNameChange: function(newName) {
this.setState({ name: newName })
},
render: function() {
return (
<div className="my-class">
<ObjectA name={ this.state.name } />
</div>
);
}
});

Related

Giving a state to parent component in React

I know you can pass down states and props in React from a parent component to a child component, but is there any way to do this the opposite way?
For example:
Given some child component:
var Child = React.createClass({
getInitialState: function(){
return {
data: ''
};
},
componentDidMount: function(){
this.setState({data: 'something'});
},
render: function() {
return (
<div>
...
</div>
);
}
});
and given some parent component:
var Parent = React.createClass({
render: function() {
return (
<div>
<Child />
...
</div>
);
}
});
Is there any way for me to give Parent the value of the state data from Child?
No.
But yes. But really no.
You cannot "pass" anything from a child to a parent in React. However, there are two solutions you can use to simulate such a passing.
1) pass a callback from the parent to the child
var Parent = React.createClass({
getInitialState: function() {
return {
names: []
};
},
addName: function(name) {
this.setState({
names: this.state.names.push(name)
});
},
render: function() {
return (
<Child
addName={this.addName}
/>
);
}
});
var Child = React.createClass({
props: {
addName: React.PropTypes.func.isRequired
},
handleAddName: function(event) {
// This is a mock
event.preventDefault();
var name = event.target.value;
this.props.addName(name);
},
render: function() {
return (
...
onClick={this.handleAddName}
...
);
}
});
The second option is to have a top-level state by using a Flux-style action/store system, such as Reflux or Redux. These basically do the same thing as the above, but are more abstract and make doing so on much larger applications very easy.
One way to do this is through a 'render props' pattern I was recently introduced to. Remember, this.props.children is really just a way for React to pass things down to a component.
For your example:
var Parent = React.createClass({
render: function() {
return (
<div>
<Child>
{(childState) => {
// render other 'grandchildren' here
}}
</Child>
</div>
);
}
});
And then in <Child> render method:
var Child = React.createClass({
propTypes: {
children: React.PropTypes.func.isRequired
},
// etc
render () {
return this.props.children(this.state);
}
});
This is probably best suited for cases where the <Child /> is responsible for doing something but doesn't really care much at all about the children that would be rendered in its place. The example the react training guys used was for a component that would fetch from Github APIs, but allow the parent to really control what / if anything was rendered with those results.

React: unnecessary component update

There are 3 react components, two of them inside of the first. The first component contains some state which used only in third component. When I update state from third component with callback react additionally update second component. But second component have no changes.
Why does this happen and how to avoid it?
here is my code:
var app = React.createClass({
displayName: 'app',
settingsChanged: function (value) {
console.log('app.settingsChanged');
this.setState({ settings: { value: value } });
},
getInitialState: function() {
return { settings: { value: 1 } }
},
render: function() {
return (
React.createElement('div', null,
React.createElement(component1),
React.createElement(component2, { settings: this.state.settings, settingsChanged: this.settingsChanged })
)
);
}
})
var component1 = React.createClass({
displayName: 'component1',
render: function () {
console.log('component1.render');
return (
React.createElement('div', null, 'component1')
);
}
})
var component2 = React.createClass({
displayName: 'component2',
tbValueChanged: function(e) {
this.props.settingsChanged(e.target.value);
},
render: function () {
console.log('component2.render');
return (
React.createElement('div', null,
React.createElement('div', null, 'component2'),
React.createElement('input', { value: this.props.settings.value, onChange: this.tbValueChanged })
)
);
}
})
In the console I see this:
component1.render app.js:27
component2.render app.js:42
app.settingsChanged app.js:5
component1.render app.js:27
component2.render app.js:42
http://jsfiddle.net/67m0z3ts/1/
Actually what's happening is a normal behaviour, once there is something changed in the main component, all components in that main one will be rendered again.
BUT the good news that you can change this default behaviour using shouldComponentUpdate(), which is true by default. Look at react.js documentation in advanced performance.
I hope that helps.
Good Luck
You can prevent React rendering with method shouldComponentUpdate.
So you have to add a these lines of code to your component1:
getInitialState : function(){
return {
shouldUpdate: true
}
},
shouldComponentUpdate: function(nextProps, nextState){
return nextState === this.state.shouldUpdate
},
And also Fiddle Link
I hope it will help you!
Thanks
I don't want to get into detail here, but in addition to other replies, you can try to enable the PureRenderMixin from React. From the docs:
Under the hood, the mixin implements shouldComponentUpdate, in which it compares the current props and state with the next ones and returns false if the equalities pass.

React: Getting an object on click

I have an array of objects which is passed as a property to a list that maps them to <li>.
I would like to be able, for any individual item, to click on an item from the list, and receive that object and then assign it to the root component's state - so I could then pass it on to another child comp.
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={function(e){console.log(e)}}>{post.title}</a></li>
})
}
</ul>)
}
})
https://jsfiddle.net/nbenita/yxw1z42q/
Thanks!
Pass a callback function into your Menu component as a prop and use Function.prototype.bind() to partially apply the relevant post object as an argument:
Updated fiddle: https://jsfiddle.net/yxw1z42q/2/
var Blog = React.createClass({
getInitialState: function() {
return {
selectedPost:this.props.posts[0]
};
},
onPostSelected: function(selectedPost) {
this.setState({
selectedPost: selectedPost
});
}
render: function() {
return (<div>
<Menu posts={this.props.posts} onClick={this.onPostSelected} />
<Post content={this.state.selectedPost} />
</div>)
}
})
var Menu = React.createClass({
render: function() {
return (<ul>
{
this.props.posts.map(function(post){
return <li><a onClick={this.props.onClick.bind(this, post)}>{post.title}</a></li>
}, this)
}
</ul>)
}
})
Further reading
React Docs - Communicate Between Components
react-training - Simple Component Communication

Call a 'Fathers' function form a 'Children' component in ReactJS

I have the next component 'Father' that contains a 'Children' component in React js.
var Father = React.createClass({
render: function () {
return (
<div>
<Children/>
</div>
);
},
onUpdate: function(state) {
this.setState(state);
} });
I want to call the onUpdate function on the father from the children BUT without calling the 'Children' method 'componentDidUpdate' because I'm using that method for some other thing that breaks my application.
How can I do that?
Pass it down in properties. If you need to update only specific parts and prevent your children from updating, use the method shouldComponentUpdate
var Father = React.createClass({
render: function () {
return (
<div>
<Children onUpdateCallback={this.onUpdate}/>
</div>
);
},
onUpdate: function(state) {
this.setState(state);
}
});
var Child = React.createClass({
render: function () { ... },
shouldComponentUpdate: function (prevProps, prevState) { ... return false}
});
If your Children can't/shouldn't update while the Parent does, I think you are probably doing something wrong, but good luck.

Passing AJAX Results As Props to Child Component

I'm trying to create a blog in React. In my main ReactBlog Component, I'm doing an AJAX call to a node server to return an array of posts. I want to pass this post data to different components as props.
In particular, I have a component called PostViewer that will show post information. I want it to by default show the post passed in from its parent via props, and otherwise show data that is set via a state call.
Currently, the relevant parts of my code looks like this.
var ReactBlog = React.createClass({
getInitialState: function() {
return {
posts: []
};
},
componentDidMount: function() {
$.get(this.props.url, function(data) {
if (this.isMounted()) {
this.setState({
posts: data
});
}
}.bind(this));
},
render: function() {
var latestPost = this.state.posts[0];
return (
<div className="layout">
<div className="layout layout-sidebar">
<PostList posts={this.state.posts}/>
</div>
<div className="layout layout-content">
<PostViewer post={latestPost}/>
</div>
</div>
)
}
});
and the child component:
var PostViewer = React.createClass({
getInitialState: function() {
return {
post: this.props.post
}
},
render: function() {
/* handle check for initial load which doesn't include prop data yet */
if (this.state.post) {
return (
<div>
{this.state.post.title}
</div>
)
}
return (
<div/>
)
}
});
The above works if I swap out the if statement and content in my child's render to this.props.* However, this would mean that I couldn't change the content later via state, correct?
TLDR: I want to set a default post to be viewed via props in a child component (results of an AJAX call), and I want to be able to change what post is being viewed by adding onClick events (of another component) that will update the state.
Is this the correct way to go about it?
Current hierarchy of my app's components are:
React Blog
- Post List
- Post Snippet (click will callback on React Blog and update Post Viewer)
- Post Viewer (default post passed in via props)
Thanks!
EDIT:
So what I ended up doing was attaching the props in ReactBlog using a value based on this.state. This ensured that it updates when I change state and renders correctly in child components. However, to do this I had to chain onClick callbacks up through all the various child components. Is this correct? It seems like it could get VERY messy. Here's my full example code:
var ReactBlog = React.createClass({
getInitialState: function() {
return {
posts: [],
};
},
componentDidMount: function() {
$.get(this.props.url, function(data) {
if (this.isMounted()) {
this.setState({
posts: data,
post: data[0]
});
}
}.bind(this));
},
focusPost: function(slug) {
$.get('/api/posts/' + slug, function(data) {
this.setState({
post: data
})
}.bind(this));
},
render: function() {
return (
<div className="layout">
<div className="layout layout-sidebar">
<PostList handleTitleClick={this.focusPost} posts={this.state.posts}/>
</div>
<div className="layout layout-content">
<PostViewer post={this.state.post}/>
</div>
</div>
)
}
});
var PostList = React.createClass({
handleTitleClick: function(slug) {
this.props.handleTitleClick(slug);
},
render: function() {
var posts = this.props.posts;
var postSnippets = posts.map(function(post, i) {
return <PostSnippet data={post} key={i} handleTitleClick={this.handleTitleClick}/>;
}, this);
return (
<div className="posts-list">
<ul>
{postSnippets}
</ul>
</div>
)
}
});
var PostSnippet = React.createClass({
handleTitleClick: function(slug) {
this.props.handleTitleClick(slug);
},
render: function() {
var post = this.props.data;
return (
<li>
<h1 onClick={this.handleTitleClick.bind(this, post.slug)}>{post.title}</h1>
</li>
)
}
});
var PostViewer = React.createClass({
getInitialState: function() {
return {
post: this.props.post
}
},
render: function() {
/* handle check for initial load which doesn't include prop data yet */
if (this.props.post) {
return (
<div>
{this.props.post.title}
</div>
)
}
return (
<div/>
)
}
});
Still hoping to get some feedback / hope this helps!
This is an old question, but I believe still relevant, so I'm going to throw in my 2 cents.
Ideally, you want to separate out any ajax calls into an actions file instead of doing it right inside a component. Without going into using something like Redux to help you manage your state (which, at this point in time, I would recommend redux + react-redux), you could use something called "container components" to do all of the heavy state lifting for you and then use props in the component that's doing the main layout. Here's an example:
// childComponent.js
import React from 'react';
import axios from 'axios'; // ajax stuff similar to jquery but with promises
const ChildComponent = React.createClass({
render: function() {
<ul className="posts">
{this.props.posts.map(function(post){
return (
<li>
<h3>{post.title}</h3>
<p>{post.content}</p>
</li>
)
})}
</ul>
}
})
const ChildComponentContainer = React.createClass({
getInitialState: function() {
return {
posts: []
}
},
componentWillMount: function() {
axios.get(this.props.url, function(resp) {
this.setState({
posts: resp.data
});
}.bind(this));
},
render: function() {
return (
<ChildComponent posts={this.state.posts} />
)
}
})
export default ChildComponentContainer;
A blog is static for the most part, so you could exploit React immutable structures to "render everything" all the time instead of using the state.
One option for this is to use a router (like page.js) to fetch data.
Here is some code http://jsbin.com/qesimopugo/1/edit?html,js,output
If you don't understand something just let me know ;)
Get rid of isMounted and make use of context if you're passing callbacks down several levels

Categories

Resources