Passing props from grandchildren to parent - javascript

I have following React.js application structure:
<App />
<BreadcrumbList>
<BreadcrumbItem />
<BreadcrumbList/>
<App />
The problem is, when I click on <BreadcrumbItem /> , I want to change a state in <App />
I used callback to pass props to <BreadcrumbList/> but that`s how far I got.
Is there any pattaren how to easily pass props up to compenent tree ?
How can I pass prop to <App />, without doing any callback chaining ?

If you are doing something simple then its often just better to pass the change in state up through the component hierarchy rather than create a store specifically for that purpose (whatever it may be). I would do the following:
BreadcrumbItem
var React = require('react/addons');
var BreadcrumbItem = React.createClass({
embiggenMenu: function() {
this.props.embiggenToggle();
},
render: function() {
return (
<div id="embiggen-sidemenu" onClick={this.embiggenMenu} />
);
}
});
module.exports = BreadcrumbItem ;
THEN pass it up to the parent through the BreadcrumbList component.....
<BreadcrumbItem embiggenToggle={this.props.embiggenToggle}>
... and UP to App, then use it to set the state....
var React = require('react/addons');
var App = React.createClass({
embiggenMenu: function() {
this.setState({
menuBig: !this.state.menuBig
});
},
render: function() {
return (
<div>
<BreadcrumbList embiggenToggle={this.embiggenMenu} />
</div>
)
}
});
module.exports = BreadcrumbItem;
This example toggles a simple boolean however you can pass up anything you like. I hope this helps.
I have not tested this but it was (quickly) ripped from a live working example.
EDIT:
As it was requested i'll expand upon the vague: "you can pass up anything".
If you were making a navigation menu based on an array and needed to pass up the selected item to a parent then you would do the following
var React = require('react/addons');
var ChildMenu = React.createClass({
getDefaultProps: function () {
return {
widgets : [
["MenuItem1"],
["MenuItem2"],
["MenuItem3"],
["MenuItem4"],
["MenuItem5"],
["MenuItem6"],
["MenuItem7"]
]
}
},
handleClick: function(i) {
console.log('You clicked: ' + this.props.widgets[i]);
this.props.onClick(this.props.widgets[i]);
},
render: function() {
return (
<nav>
<ul>
{this.props.widgets.map(function(item, i) {
var Label = item[0];
return (
<li
onClick={this.handleClick.bind(this, i)}
key={i}>
{Label}
</li>
);
}, this)}
</ul>
</nav>
);
}
});
module.exports = ChildMenu;
You would then do the following in the parent:
var React = require('react/addons');
var ChildMenuBar = require('./app/top-bar.jsx');
var ParentApp = React.createClass({
widgetSelectedClick: function(selection) {
//LOGGING
//console.log('THE APP LOGS: ' + selection);
//VARIABLE SETTING
var widgetName = selection[0];
//YOU CAN THEN USE THIS "selection"
//THIS SETS THE APP STATE
this.setState({
currentWidget: widgetName
});
},
render: function() {
return (
<ChildMenu onClick={this.widgetSelectedClick} />
);
}
});
module.exports = ParentApp;
I hope this helps. Thanks for the upvote.

If you use Flux pattern, you can have a AppStore which listen a BREADCRUMB_CLICK event. So when you click on a BreadCrumbItem, you can execute an action which dispatch BREADCRUMB_CLICK event. When AppStore handle the event, he inform App component which update your state.
For more informations:
Flux architecture

Related

Can't call function in parent component from child component using React

I have 2 files:
grid-body.jsx (GridBody) and grid-row.jsx (GridRow)
In GridBody, I declared a function showAlert which I pass to every GridRow:
var GridBody = React.createClass({
showAlert: function(msg) {
alert(msg);
},
render: function() {
var rows = this.props.rows.map(function(li) {
return (
<GridRow showAlert={this.showAlert} />
);
});
return (
<div>
{rows}
</div>
);
}
});
And in GridRow:
var GridRow = React.createClass({
toggle: function() {
this.props.showAlert('HEY'); // -----> ERROR - not a function
},
render: function() {
<div>
<a href="#" onClick={this.toggle} />
</div>
}
});
I'm trying to call the showAlert from parent and based on the examples I've seen, this is how to do it but I can't make it work.
you're using the wrong value for this inside of GridView.render. Either pass it explicitly to Array.map() (see the docs for how to do that) or assign this to some new variable at the very top of render() and reference that instead.
Here is a really, really great SO comment as to why this happens, as well as some other alternative workarounds if neither of the above work for you.
The context of the function passed to map in render method of GridBody is window and not the component. You can bind the interatee to get the behavior you want:
render: function() {
var rows = this.props.rows.map(function(li) {
return (
<GridRow showAlert={this.showAlert} />
);
}.bind(this));
return (
<div>
{rows}
</div>
);
}

Passing Parameters to Components in React Native

I'm trying to use a common Navigation Component I made in React-Native. At the point of calling I want to set the Navigation Bar Tint, Title etc.
Nav Bar Code:
var NavigationBar = React.createClass({
render: function(title, titleColor, NavBarColor) {
var titleConfig = {
title: title,
tintColor: titleColor,
};
return (
<NavBar
title={titleConfig}
tintColor={NavBarColor}
leftButton={<Button style={styles.menuButton}></Button>}
rightButton={<Button style={styles.menuButton}></Button>} />
);
}
});
Applying it on another page:
<NavigationBar title="Categories" titleColor="#ffffff" NavBarColor="#f0b210"/>
How to do this properly? Thanks in advance.
First off render does not take any parameters, what you want to do is to reference your props that you passed in.
render: function () {
var titleConfig = {
title: this.props.title,
tintColor: this.props.titleColor
};
// Rest of code
}
Just by doing this, whenever your NavigationBar rerenders so will the NavBar component too.
A super simple example demonstrating this
var NavBar = React.createClass({
render: function () {
return <div id="navbar" style={{backgroundColor: this.props.tintColor}}>
<h1 style={{color: this.props.title.tintColor}}>{this.props.title.title}</h1>
</div>;
}
});
var NavigationBar = React.createClass({
render: function() {
var titleConfig = {
title: this.props.title,
tintColor: this.props.titleColor,
};
return (
<NavBar
title={titleConfig}
tintColor={this.props.NavBarColor}
/>
);
}
});
React.render(<NavigationBar title="Categories" titleColor="#ff0" NavBarColor="#f0b210" />, document.body);
You Can call the Navigation bar component and giving the props like this
let inputProps={
color:"blue",
title:"Title"
};
<NavigationBar props={inputProps}/>
And in the declaration of NavigationBar you can use it like this
const NavigationBar = (props)=>{
const [title,setTitle] = useState("");
const [color,setColor] = useState("");
useEffect(()=>{
setColor(props.color);
setTitle(props.title);
},[props.color,props.title]);
return(
<NavBar
title={title}
tintColor={color}
leftButton={<Button style={styles.menuButton}></Button>}
rightButton={
<Button style={styles.menuButton}></Button>}
/>
);
}
As your the color and the title changes the effect hook will trigger and update the state of the title and color using the state hook which will force the component to re-render with updated values.So its one way binding giving you a flavour of two way binding.
The render is a non-parametrised function means it does not take any parameter. So to pass parameters/value from one component to other in React Native we use props. The props is a JavaScript object that has property to pass on from one component to others.
So, you need to pass the values with props.

Get value from input and use on the button

I'am creating component with input element and button element.
I need to get the input value and use with button, for example. How can I do that?
Here's my code:
var InputSearch = React.createClass({
getInitialState: function() {
return {
value: 'pics'
}
},
handleChange: function() {
this.setState({
value: event.target.value
});
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
)
}
});
var ButtonSearch = React.createClass({
handleClick: function(event) {
console.log(this.state.value); // here's go the input value
},
render: function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
var Search = React.createClass({
render: function() {
return (
<div>
<InputSearch />
<ButtonSearch />
</div>
)
}
});
React.render(
<Search />,
document.getElementById('result')
);
One issue here is that you are breaking a good rule - separate smart and dumb components. https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
The way to do this is to have a parent component that holds all the state and functionality of the children and passes all of this down as props...
//Our smart parent
var SearchContainer = React.createClass({
getInitialState : function() {
return {
value : 'pics'
}
},
handleInput : function(event) {
this.setState({value: event.target.value});
},
render : function() {
return (
<div>
<InputSearch value={this.state.value} onChange={this.handleInput} />
<ButtonSearch value={this.state.value} />
</div>
)
}
});
//Our dumb children
var InputSearch = React.createClass({
propTypes : {
onChange : React.PropTypes.func.isRequired,
value : React.PropTypes.string
},
render : function() {
return (
<input type="text" value={this.props.value} onChange={this.props.onChange} />
)
}
});
var ButtonSearch = React.createClass({
propTypes : {
value : React.PropTypes.string
},
handleClick : function() {
console.log(this.props.value); //log value
},
render : function() {
return (
<button onClick={this.handleClick}>GO! </button>
)
}
});
React.render(<Search />, document.getElementById('result'));
Here we pass the handler function down from parent to child so the input doesn't care what happens to the event it fires on change, it just needs to know that it has a prop called onChange that's a function and it invokes that.
The parent (SearchContainer) handles all of that functionality and passes the changed state down to both the button and the input...
hope that helps
Dan
You left out the event in your handleChange.
handleChange: function(event) {
this.setState({
value: event.target.value
});
},
The main architecture of react is the Parent Child / Master Slave principle.
If you want to pass values between components you have to create relations between.
Like for example
You create your master Component with few default states.
var MyMasterComponent = React.createClass({
getInitialState: function(){
...
},
render: function(){
return(
<ChilComponent1 textiwanttopass={this.state.text} />
);
}
});
With that method you are calling the render of another component within a master component. That way you can pass values from states into another component.
In that case you can access the passed text with this.props.textiwanttopass

React JS - What is a good way to handle children click event?

I have a list with around 2k items. If I use onClick on each child, I would end up with 2k listeners which is what I have currently. I would want to do something like making the parent component listen to the click events instead. But if I do that, I don't have reference to the child component which I need to call setState on. Also the list of child components can be filtered dynamically (using this.refs might be bad ?).
The best I can come up with is to make a hash of child components id mapping to child components in the parent and look up the view on click.
Just for illustration purposes:
var Parent = React.createClass({
shouldComponentUpdate: function() { return false; },
handler: function(e) {
// look up from reference and set state
},
componentWillUnmount: function() {
// clean up reference
},
render: function() {
this.reference = {};
var items = [];
for(var i = 0; i < this.props.items.length; i++) {
var child = React.createClass(Child, {id: this.props.items[i].id});
items.push(child);
reference[child.id] = child;
}
return React.createClass('div', {onClick: this.handler}, items);
}
})
I wonder if there is a React way of dealing with this.
I think this answer may help... It does not matter if you have 2000 event handlers or just one. React deals with it in the same way. Remember that the HTML you return in your render method does not get added to the DOM but it is just used by React to build a virtual DOM representation. In the end, React has only one onClick.
React efficient way to bind event to many dom elements
If you need to know what element triggered the click you just need to access event.target and use any data-attribute to identify the clicked element.
The React way of doing this would be to use a Flux dispatcher + a Store. Basically, you can have each item bind to an event that gets triggered from the store once the store has carried out the tasks you want it to complete.
So the flow will be:
Item gets clicked => Flux event is dispatched => Flux dispatcher hears the events and executes the appropriate function with the data passed from Item component.
var ItemStore = {
doSomething: function(data){
// do something with the data
}
}
MicroEvent.mixin(ItemStore);
var AppDispatcher = new Dispatcher();
AppDispatcher.register(function(payload) {
switch (payload.eventName) {
case 'item-clicked':
ItemStore.doSomething(payload.data.someData);
ItemStore.trigger('did-something');
}
return true;
})
var Item = React.createClass({
shouldComponentUpdate: function() { return false; },
componentDidMount: function() {
ItemStore.bind('did-something', this.submitHandled);
},
handler: function(e) {
AppDispatcher.dispatch({
eventName: 'item-clicked',
data: {
someData: 'sample data'
}
});
},
componentWillUnmount: function() {
// clean up reference
},
submitHandled: function() {
// do something after the click
},
render: function() {
// insert your item's html here.
}
})
Building on #damianmr's answer, here's an example.
var Child = React.createClass({
shouldComponentUpdate(nextProps){
if (this.props.text !== nextProps.text) return true;
if (this.props.active !== nextProps.active) return true;
return false;
},
render(){
var className = 'Child';
if (this.props.active) className += ' Child-active';
return (
<div {...this.props} className={className}>
{this.props.text}
</div>
);
}
});
var Parent = React.createClass({
getInitialState(){
return {active: -1};
},
setActive(id){
this.setState({active: id});
},
render(){
return (
<div>
{this.props.items.map((item) => {
return (
<Child
active={this.state.active === item.id}
onClick={() => this.setActive(item.id)}
text={'My id is ' + item.id}
key={item.id}
/>
);
})}
</div>
);
}
});

ReactJS. Quite slow when rendering and updating a simple list of 1500 <li> elements. I thought VirtualDOM was fast

I was really disappointed by the performance I got on the following simple ReactJS example. When clicking on an item, the label (count) gets updated accordingly. Unfortunately, this takes roughly ~0.5-1 second to get updated. That's mainly due to "re-rendering" the entire todo list.
My understanding is that React's key design decision is to make the API seem like it re-renders the whole app on every update. It is supposed take the current state of the DOM and compare it with the target DOM representation, do a diff and update only the things that need to get updated.
Am I doing something which is not optimal? I could always update the count label manually (and the state silently) and that will be an almost instant operation but that takes away the point of using ReactJS.
/** #jsx React.DOM */
TodoItem = React.createClass({
getDefaultProps: function () {
return {
completedCallback: function () {
console.log('not callback provided');
}
};
},
getInitialState: function () {
return this.props;
},
updateCompletedState: function () {
var isCompleted = !this.state.data.completed;
this.setState(_.extend(this.state.data, {
completed: isCompleted
}));
this.props.completedCallback(isCompleted);
},
render: function () {
var renderContext = this.state.data ?
(<li className={'todo-item' + (this.state.data.completed ? ' ' + 'strike-through' : '')}>
<input onClick={this.updateCompletedState} type="checkbox" checked={this.state.data.completed ? 'checked' : ''} />
<span onClick={this.updateCompletedState} className="description">{this.state.data.description}</span>
</li>) : null;
return renderContext;
}
});
var TodoList = React.createClass({
getInitialState: function () {
return {
todoItems: this.props.data.todoItems,
completedTodoItemsCount: 0
};
},
updateCount: function (isCompleted) {
this.setState(_.extend(this.state, {
completedTodoItemsCount: isCompleted ? this.state.completedTodoItemsCount + 1 : this.state.completedTodoItemsCount - 1
}));
},
render: function () {
var updateCount = this.updateCount;
return (
<div>
<div>count: {this.state.completedTodoItemsCount}</div>
<ul className="todo-list">
{ this.state.todoItems.map(function (todoItem) {
return <TodoItem data={ todoItem } completedCallback={ updateCount } />
}) }
</ul>
</div>
);
}
});
var data = {todoItems: []}, i = 0;
while(i++ < 1000) {
data.todoItems.push({description: 'Comment ' + i, completed: false});
}
React.renderComponent(<TodoList data={ data } />, document.body);
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
jsFiddle link, just in case: http://jsfiddle.net/9nrnz1qm/3/
If you do the following, you can cut the time down by a lot. It spends 25ms to 45ms to update for me.
use the production build
implement shouldComponentUpdate
update the state immutably
updateCompletedState: function (event) {
var isCompleted = event.target.checked;
this.setState({data:
_.extend({}, this.state.data, {
completed: isCompleted
})
});
this.props.completedCallback(isCompleted);
},
shouldComponentUpdate: function(nextProps, nextState){
return nextState.data.completed !== this.state.data.completed;
},
Updated fiddle
(there are a lot of questionable things about this code, daniula points out some of them)
When you are generating list of elements you should provide unique key prop for everyone. In your case:
<ul className="todo-list">
{ this.state.todoItems.map(function (todoItem, i) {
return <TodoItem key={i} data={ todoItem } completedCallback={ updateCount } />
}) }
</ul>
You can find out about this mistake by warning message in browser console:
Each child in an array should have a unique "key" prop. Check the render method of TodoList. See fb.me/react-warning-keys for more information.
There is another warning which you can easily fix by changing event handler on <input type="checkbox" /> inside <TodoItem /> from onClick to onChange:
<input onClick={this.updateCompletedState} type="checkbox" checked={this.state.data.completed ? 'checked' : ''} />
You are doing some string concatenation to set proper className. For more readable code try using nice and simple React.addons.classSet:
render: function () {
var renderContext = this.state.data ?
var cx = React.addons.classSet({
'todo-item': true,
'strike-through': this.state.data.completed
});
(<li className={ cx }>
<input onChange={this.updateCompletedState} type="checkbox" checked={this.state.data.completed ? 'checked' : ''} />
<span onClick={this.updateCompletedState} className="description">{this.state.data.description}</span>
</li>) : null;
return renderContext;
}
I'm looking at where you render() the list...
<div>
<div>count: {this.state.completedTodoItemsCount}</div>
<ul className="todo-list">
{ this.state.todoItems.map(function (todoItem) {
return <TodoItem data={ todoItem } completedCallback={ updateCount } />
}) }
</ul>
</div>
This should not be called every time a TodoItem is updated. Give the above element a surrounding div and an id like this:
return <div id={someindex++}><TodoItem
data={ todoItem }
completedCallback={ updateCount }
/></div>
Then simply rerender a single TodoItem as it is changed, like so:
ReactDOM.render(<TodoItem ...>, document.getElementById('someindex'));
ReactJS is supposed to be fast, yes, but you still need to stick to general programming paradigms, i.e., asking the machine to do as little as possible, thereby producing the result as fast as possible. Rerendering stuff that doesn't need to get re-rendered gets in the way of that, whether or not it's "best practice".

Categories