Coordinating props of encapsulated components when rendering data in reactjs - reactjs

I am building a recipe box in reactJS. My objective is hide ingredients within the button, listing the recipe title. Thus when a person clicks on a button titled "cheesecake" they will see its respective ingredients. The booleans in communicating when and when not to do this makes sense as it relates to "Onclick". However, I'm unsure of how to coordinate this action when fetching data given that my ingredients data (this.props.ingredients) is implicated within recipetitlebutton component. I tried re-initializing the ingredients component within the title button thinking that I can just define it within the recipeTitleButton when I mapped over the data. However, this didn't work and it didn't feel clean. Anyway, I hope this makes sense. Any help is greatly appreciated.
Thanks
var recipes = [{
recipe_title: "Cheesecake",
ingredients: "cream cheese, graham crackers, butter, eggs"
}, {
recipe_title: "Lasagna",
ingredients: " ricotta cheese, ground beef, pasta shells, parsely"
}, {
recipe_title: "Spaghetti",
ingredients: "noodles, pasta sauce, ground beef"
}]
var RecipeTitleButton = React.createClass({
getInitialState: function() {
return {
showIngredients: false
}
},
onClick: function() {
this.setState({
showIngredients: true
})
},
render: function() {
<Ingredients ingredients={this.props.ingredients}/>
return (
<div>
<button type="button" className="recipe_title_button" class="btn btn=primary btn-lg">{this.props.recipe_title}</button>
{this.state.showIngredients ? <Ingredients/>: null}
</div>
)
}
})
var Ingredients = React.createClass({
render: function() {
return (
<div id="ingredients" className="recipe_title_ingredients">
{this.props.ingredients}
</div>
)
}
})
var MainRecipeDisplay = React.createClass({
getInitialState: function() {
return {
recipeDataObject: recipes
}
},
render: function() {
var Pages = this.state.recipeDataObject.map(function(recipeContents) {
<RecipeTitleButton recipe_title={recipeContents.recipe_title} ingredients={recipeContents.ingredients}/>
})
return (
<div>
{Pages}
</div>
)
}
})
ReactDOM.render(<MainRecipeDisplay/>, document.getElementById('content'))

It appears that you're not actually passing the click handler to any of the elements. So you've defined the onClick method in RecipeTitleButton, but you're not passing this to anything. The solution is probably as simple as passing the <button> element a property onClick={/* The function that you want to fire on click */}.
First of all, change the name of the click handler to something like onClickHandler, for sanity. Click handlers are called with an event argument, which you probably don't need for your purposes but is important to know about (for example, if you need to prevent event propagation or have the click handler figure out which button was clicked).
Then the render function for RecipeTitleButton should look like:
render: function() {
<Ingredients ingredients={this.props.ingredients}/>
return (
<div>
<button type="button" className="recipe_title_button" onClick={this.onClickHandler.bind(this)} class="btn btn=primary btn-lg">{this.props.recipe_title}</button>
{this.state.showIngredients ? <Ingredients/>: null}
</div>
)
}
In case you're wondering, we bind the function to this so that the context remains the RecipeTitleButton component, instead of the window.
Oh, as an aside, it'd be easier to test this if you put it in a JSFiddle

Actually I figured it out. Was very simple. First, React doesn't recognize changing the setState value with a mere {setState({showingredients: true}). I had to use a function to make this explicit {setState(function(){return showIngredients:true)}. Second,in order to render the ingredients component within in my recipeTitle component, I only had to indicate props within {this.showIngredients ? :"null"/>. This way, I was allowed to define the ingredients prop within my recipeTitleButton. Code is Below:
var recipes = [{
title: "Cheesecake",
ingredients: "cream cheese, graham crackers, butter, eggs"
}, {
title: "Lasagna",
ingredients: " ricotta cheese, ground beef, pasta shells, parsely"
}, {
title: "Spaghetti",
ingredients: "noodles, pasta sauce, ground beef"
}]
var Layout = React.createClass({
getInitialState: function() {
return {
recipeDataObject: recipes,
showIngredients: false
}
},
render: function() {
var recipeContents = this.state.recipeDataObject.map(function(currentRecipe) {
return (
<RecipeTitleButton title={currentRecipe.title} ingredients={currentRecipe.ingredients}/>
)
})
return (
<div>
{recipeContents}
</div>
)
}
})
var RecipeTitleButton = React.createClass({
getInitialState: function() {
return {
showIngredients: false
}
},
handleRecipeButtonClick: function() {
**this.setState(function() {
return {
showIngredients: true
}**
});
},
render: function() {
return (
<div>
<button type="button" onClick={this.handleRecipeButtonClick.bind(this)} className="recipe_button">{this.props.title}</button>
**{this.state.showIngredients && <Ingredients ingredients={this.props.ingredients}/>}**
</div>
)
}
})
var Ingredients = React.createClass({
render: function(){
return(
<div className= "ingredients_list">
{this.props.ingredients}
</div>
)
}
})

Related

React Cannot read property '__reactInternalInstance$2f71vks24hx' of null [duplicate]

Here is the problematic component in question.
const UserList = React.createClass({
render: function(){
let theList;
if(this.props.data){
theList=this.props.data.map(function(user, pos){
return (
<div className="row user">
<div className="col-xs-1">{pos}</div>
<div className="col-xs-5">{user.username}</div>
<div className="col-xs-3">{user.recent}</div>
<div className="col-xs-3">{user.alltime}</div>
</div>
);
}, this);
} else {
theList = <div>I don't know anymore</div>;
}
console.log(theList);
return (
theList
);
}
});
Whenever I attempt to return {theList}, I receive a Cannot read property '__reactInternalInstance$mincana79xce0t6kk1s5g66r' of null error. However, if I replace {theList} with static html, console.log prints out the correct array of objects that i want. As per the answers, I have tried to return both {theList} and theList but that didn't help.
In both cases, console.log first prints out [] which I assume is because componentDidMount contains my ajax call to get json from the server and has not fired yet before the first render(). I have tried to check against
this.props.data being null but it does not help.
Here is the parent component if it helps:
const Leaderboard = React.createClass({
getInitialState: function(){
return ({data: [], mode: 0});
},
componentDidMount: function(){
$.ajax({
url: 'https://someurlthatreturnsjson',
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('https://someurlthatreturnsjson', status, err.toString());
}.bind(this)
});
},
render: function(){
return (
<div className="leaderboard">
<div className="row titleBar">
<img src="http://someimage.jpg"></img>Leaderboard
</div>
<HeaderBar />
<UserList data={this.state.data}/>
</div>
);
}
});
Ah OK, there were some interesting problems in here, but you were so close. The big one, with react you must always return a single top-level element (e.g. a div). So, your variable theList was actually an array of divs. You can't return that directly. But you can return it if it's wrapped in a single parent div.
const mockData = [
{
username: 'bob',
recent: 'seven',
alltime: 123,
},
{
username: 'sally mae',
recent: 'seven',
alltime: 133999,
},
];
var $ = {
ajax(opt) {
setTimeout(() => {
opt.success(mockData);
}, 200);
}
}
const UserList = React.createClass({
render: function(){
let theList;
if (this.props.data && this.props.data.length) {
theList = this.props.data.map(function(user, pos){
return (
<div key={user.username} className="row user">
<div className="col">{pos}</div>
<div className="col">{user.username}</div>
<div className="col">{user.recent}</div>
<div className="col">{user.alltime}</div>
</div>
);
});
} else {
theList = <div>There is NO data</div>;
}
return <div>{theList}</div>;
}
});
const Leaderboard = React.createClass({
getInitialState: function(){
return ({data: [], mode: 0});
},
componentDidMount: function(){
$.ajax({
url: 'https://someurlthatreturnsjson',
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('https://someurlthatreturnsjson', status, err.toString());
}.bind(this)
});
},
render: function(){
return (
<div className="leaderboard">
<UserList data={this.state.data}/>
</div>
);
}
});
ReactDOM.render(
<Leaderboard/>,
document.getElementById('container')
);
.col {
width: 200px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
To explain the fiddle a little bit. Don't worry about the weird looking var $ stuff, I'm just stubbing out jQuery's ajax method so I can return some fake data after 200ms.
Also, for me jsfiddle gives me a 'bad config' message when I run it, but I close the message and the result is there. Don't know what that's about.
return (
{theList}
)
should just be
return theList
because you are not inside JSX at that point. What you're doing there will be interpreted as
return {
theList: theList
}
That's ES6 shorthand properties syntax.
Error can also arise from accessing nested state that doesn't exist:
I lack the reputation to comment, so adding an answer for future assistance -- I ran into this same issue for a different reason. Apparently, the error is triggered from an earlier error throwing off react's internal state, but the error is getting caught somehow. github issue #8091
In my case, I was trying access a property of state that didn't exist after moving the property to redux store:
// original state
state: {
files: [],
user: {},
}
// ... within render function:
<h1> Welcome {this.state.user.username} </h1>
I subsequently moved user to redux store and deleted line from state
// modified state
state: {
files: [],
}
// ... within render function (forgot to modify):
<h1> Welcome {this.state.user.username} </h1>
And this threw the cryptic error. Everything was cleared up by modifying render to call on this.props.user.username.
There is a small problem with the if statement:
if(this.props.data !== []){
should be:
if(this.props.data){
this.props.data is null, if the ajax call returns null. alternatively the code could be more elaborate.
const data = this.props.data;
if(data && data.constructor === Array && data.length > 0) {
Not sure if this is how you want to do it, but it works for me.
edit:
const UserList = React.createClass({
render: function() {
if(this.props.data){
return this.props.data.map(function(user, pos){
return (
<li> className="row user">
<span>{pos}</span>
<span>{user.username}</span>
<span>{user.recent}</span>
<span>{user.alltime}</span>
</li>
);
});
} else {
return <li>I don't know anymore</li>;
}
}
});
I encountered this error when I rendered a stateless component and decided to remove the react-root-element (wrapping div) after rendering it with basic dom manipulation.
Conclusion: be aware of this, better don't do it.

react components not talking to each other

I've built a basic restuarant recommendation app that filters by location using the YELP api. The api was responding to my requests with the response object and everything was appending to my divs perfectly, but I realized that for my project, I needed to make a new layer for the data listing. Here are the relevant portions of my two components as they are now:
display-recs:
var DisplayRecs = React.createClass({
render: function() {
var recsLoop = [];
if (this.props.recommendations) {
for (var i=0; i < this.props.recommendations.length; i++) {
recsLoop.push(<Recommendations item={this.props.recommendations[i]} />)
}
}
console.log(this.props.recommendations);
return (
<div className="DisplayRecs">
{recsLoop}
</div>
);
}
});
var mapStateToProps = function(state, props) {
return {
recommendations: state.recommendations
};
};
recommendations:
var Recommendations = React.createClass({
render: function() {
<div id="bizData">
<div id='nameList'>{this.props.item.name}</div>
<div id='phoneList'>{this.props.item.phone}</div>
<div id='ratingList'>{this.props.item.rating}</div>
</div>
}
});
var mapStateToProps = function(state, props) {
return {
recommendations: state.recommendations
};
};
I cannot figure out why the nameList, phoneList, and ratingList will not print onto the dom. When I view the elements tab in my devtools, all i see is an empty displayrecs div. I've tried to just change things by guessing, but it's not been fruitful. Can any of you see an obvious problem with the current code?
Thanks
Your Recommendations react component's render function doesn't have any return statement. Try doing this:
var Recommendations = React.createClass({
render: function() {
return ( <div id="bizData">
<div id='nameList'>{this.props.item.name}</div>
<div id='phoneList'>{this.props.item.phone}</div>
<div id='ratingList'>{this.props.item.rating}</div>
</div>);
}
});
Also add a key to the Recommendations components as #Vikramaditya recommends:
recsLoop.push(<Recommendations key={i} item={this.props.recommendations[i]} />)

Add event handler to React.DOM element dynamically

I'm working with a RadioButtonGroup component which is like radio input but with buttons:
It would be good if using the component was easy like this:
var SelectThing = React.createClass({
render: function render() {
// I would not like to add onClick handler to every button element
// outside the RadioButtonGroup component
return (
<RadioButtonGroup onChange={this._onActiveChange}>
<button>Thing 1</button>
<button>Thing 2</button>
<button>Thing 3</button>
</RadioButtonGroup>
)
},
_onActiveChange: function _onActiveChange(index) {
console.log('You clicked button with index:', index);
}
});
The actual question: How can I achieve that the most elegantly with React? (I found another similar question but it doesn't exactly answer to this).
My first intuition was to add and remove the onClick handlers inside the component to remove boiler plate code from the component's user. Another option that comes to my mind is to give e.g. <p> elements instead of button elements and put them inside button elements which would be created inside the RadioButtonGroup component. I don't like the latter that much because it doesn't make that much sense semantically compared to passing buttons.
Here's what the (obviously not working) component looks like now:
// Radio input with buttons
// http://getbootstrap.com/javascript/#buttons-checkbox-radio
var RadioButtonGroup = React.createClass({
getInitialState: function getInitialState() {
return {
active: this.props.active || 0
};
},
componentWillMount: function componentWillMount() {
var buttons = this.props.children;
buttons[this.props.active].className += ' active';
var self = this;
buttons.forEach(function(button, index) {
// How to dynamically set onclick handler for virtual dom
// element created inside JSX?
button.addEventListener('onClick', function(event) {
self._onAnyButtonClick(index, event);
}
});
},
componentWillUnmount: function componentWillUnmount() {
var buttons = this.props.children;
buttons.forEach(function(button, index) {
button.removeEventListener('onClick');
});
},
render: function render() {
return (
<div className="radio-button-group">
{buttons}
</div>
)
},
_onAnyButtonClick: function _onAnyButtonClick(index, event) {
this.setState({
active: index
});
this.props.onChange(index);
}
});
You don't want to mess with click handlers on each button, just listen for the click on the container. Then update the state based on which child is clicked.
Also, with React it's best to keep all of your DOM stuff in the render function. In this case, defining an element's class name.
Here's how this could work:
var RadioButtonGroup = React.createClass({
getInitialState: function getInitialState() {
return {
active: this.props.active || 0
};
},
clickHandler: function clickHandler(e) {
// Getting an array of DOM elements
// Then finding which element was clicked
var nodes = Array.prototype.slice.call( e.currentTarget.children );
var index = nodes.indexOf( e.target );
this.setState({ active: index });
},
render: function render() {
var buttons = this.children.map(function(child, i) {
if (i === this.state.active) child.props.className += ' active';
return child;
}, this);
return (
<div className="radio-button-group" onClick={ this.clickHandler }>
{ buttons }
</div>
)
}
});
To get an api like this (similar to <input/>), we need to use the cloneWithProps addon.
<RadioButtonGroup onChange={this.handleChange} value={this.state.selected}>
<button>Test 1</button>
<button>Test 2</button>
<button>Test 3</button>
</RadioButtonGroup>
All this does is take each child, add a click handler, and conditionally add a className of 'active' to it. You easily can (and should) modify it to take the active class name as a prop.
var RadioButtonGroup = React.createClass({
render: function(){
return <div>{React.Children.map(this.props.children, this.renderItem)}</div>
},
renderItem: function(button, index){
return React.cloneElement(button, {
className: this.props.value === index ? ' active ' : '',
onClick: function(){
this.props.onChange(index);
}.bind(this),
key: index
});
}
});
demo
If you don't want to use cloneWithProps, you could use a wrapper div, but styling may be a bit more complex.
renderItem: function(button, index){
return React.createElement('div', {
className: this.props.value === index ? ' active ' : '',
onClick: function(){
this.props.onChange(index);
}.bind(this),
key: index
}, button);
}
The reason everything uses index is because you're passing react elements, which are opaque. There's no clean way to get any data out of these buttons, but we do know their index because we're iterating over them using React.Children.map. An alternative api would look like this:
<RadioButtonGroup value={'test1'} onChange={fn} options={{
test1: <button>Test 1</button>,
test2: <button>Test 2</button>,
test3: <button>Test 3</button>
}} />
Here we can iterate over this.props.options, and pass the key to the onChange callback, and take e.g. 'test1' as a value prop.
This is my code .I do not know whether this is the best way ,as i started using react just 5 hrs ago. But it works fine.
var LeftPane = React.createClass({
getInitialState: function() {
return {list:[{name:"Item 1",isactive:1},
{name:"Item 2",isactive:0},
{name:"Item 3",isactive:0},
{name:"Item 4",isactive:0},
{name:"Item 5",isactive:0}]};
},
clickHandler: function(index) {
var current_list = this.state.list;
current_list.map(function(record,i){
if(record.isactive==1){
if(i!=index){
record.isactive =0;
}else{
return;
}
}else{
if(i==index){
record.isactive =1;
}
}
});
this.setState({data:current_list});
},
render: function() {
var active_item = "list-group-item active"
var non_active_item ="list-group-item";
var _this = this;
return (
<div className="list-group">
{this.state.list.map(function(record,i) {
if(record.isactive==1){
return <a className={active_item} onClick={_this.clickHandler.bind(null, i)}>{record.name}</a>
}else{
return <a className={non_active_item} onClick={_this.clickHandler.bind(null, i)}>{record.name}</a>
}
})}
</div>
</div>
)
}
});
I would not like to add onClick handler to every button element
React uses events delegation pattern, so you can freely adding as many onClick handlers as needs.
Another way, if you just want to make code clear, you may create your own button component, and pass _onActiveChange to it props, but i don't sure that it's necessary in your case.
And remember, that React works with synthetic events, and, in some cases, usage of setState within native event handlers may cause an unpredictable behaviour.

ReactJS: How can I get the owner of a component?

ReactJS encourages one-way data flow but I want to break it for easier development where I need to two-way bound Input box.
I want a component like this
var App = React.createClass({
getInitialState: function(){
return {
user: {
name: ''
}
}
},
render: function(){
return <TwoWayBinder type="input" model="user.name" />;
}
});
where user.name is a variable in this.state. So, I want <TwoWayBinder /> component to access the state of it's parent component (which is an anti-pattern according to React philosophy). I see that parent component is available in _owner property of TwoWayBinder component.
Is that the only way to access the owner? I don't want to use valueLink for multiple reasons.
There is no documented api for accessing the owner. _owner is the only undocumented way (as far as I know).
Update: "component._owner is no longer available in 0.13" -zbyte
I'm not a fan of valueLink personally. I've been working on a similar but more powerful system.
In its lowest level form your code looks like this: jsbin 1
var App = React.createClass({
mixins: [formMixin],
getInitialState: function(){
return {
data: { name: "", email: "" }
}
},
render: function(){
var formData = this.stateKey("data");
return (
<div>
<input type="text" value={this.state.data.name} onChange={formData.forKey("name").handler()} />
<input type="text" value={this.state.data.email} onChange={formData.forKey("email").handler() } />
</div>
);
}
});
That's not bad, and gives you a lot of control, but you might want something even quicker. jsbin 2
var Input = React.createClass({
render: function(){
var link = this.props.link;
return <input type="text"
{...this.props}
value={link.getCurrentValue()}
onChange={link.handler()} />
}
});
var App = React.createClass({
mixins: [formMixin],
getInitialState: function(){
return { data: { name: "", email: "" } }
}
},
render: function(){
var formData = this.stateKey("data");
return (
<div>
<Input link={formData.forKey("name")} />
<Input link={formData.forKey("email")} />
</div>
);
}
});
For completeness, here's the full mixin:
var formMixinHandler=function(thisArg,keys,parent){return{forKey:function(key){return formMixinHandler(thisArg,keys.concat(key),this)},bindTo:function(newThisArg){return formMixinHandler(newThisArg,keys,this)},transform:function(fn){var obj=formMixinHandler(thisArg,keys,this);obj.transforms=obj.transforms.concat(fn);return obj},transforms:parent?parent.transforms:[],handler:function(){var self=this;return function(event){var value=event;if(event.target instanceof HTMLInputElement)if(event.target.type==="checkbox"||event.target.type==="radio")value=event.target.checked;else value=event.target.value;self.transforms.reduce(function(last,fn){return fn(last,event)},value);var targetObj=keys.slice(0,-1).reduce(function(obj,key){if(!obj[key])obj[key]={};return obj[key]},thisArg.state);targetObj[keys[keys.length-1]]=value;var updateObject={};updateObject[keys[0]]=thisArg.state[keys[0]];thisArg.setState(updateObject)}},getCurrentValue:function(){return keys.reduce(function(obj,key){return obj?obj[key]:null},thisArg.state)}}};var formMixin={stateKey:function(key){return formMixinHandler(this,[].concat(key))}};
Just for the question, there is really internal API to get the owner in version 0.13:
this._reactInternalInstance._currentElement._owner._instance
As you know, it's really not recommended.

React CCSTransitionGroup animation not applying enter/leave classes

I'm trying to write a simple page slider. Here, when I click a page, it creates a new Page with random content, and re-renders the App component. On App render(), instead of the TransitionGroup holding both state.pages until animation completes, it just switches out the pages, never attaching the enter-leave classes and not performing the css animation. I'm sure I'm messing something up in the LifeCycle, but can't think of it.
Thanks for looking!
var Page = React.createClass({
handleClick: function(){
var pgs = ['page-one','page-two','page-three','page-four']
currentIdx = Math.floor(Math.random() * pgs.length);
var pg = pgs[ currentIdx ];
var newPg = <Page html={pg} title={'Title for ' + pg} />;
React.renderComponent(<App newPage={newPg} />, document.body)
},
render: function(){
return (<div className="content" style={{paddingTop: 44}} onClick={this.handleClick}>{this.props.html}</div>);
}
})
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var App = React.createClass({
getInitialState: function() {
return {pages: [<Page html="initial page" title="initial title" />]};
},
componentWillMount: function(){
this.setState({pages: [this.props.newPage]})
},
componentWillReceiveProps: function(nextProps) {
this.setState({pages: [nextProps.newPage]});
},
render: function() {
var title = this.state.pages.length ? this.state.pages[ this.state.pages.length - 1 ].props.title : 'none';
return (
<div id="body">
<TitleBar title={title} />
<ReactCSSTransitionGroup transitionName="pg" id="transdiv" component={React.DOM.div}>
{this.state.pages}
</ReactCSSTransitionGroup>
</div>
);
}
});
The problem was that I was setting the Page keys in Page.render() (not shown above), and not in App.render() I'm not sure why you can't set keys in the child/owned component as long as they're unique, but this fixed my problem.
var App = React.createClass({
// other methods are same
render: function(){
var title = 'Title';
var pgs = this.state.pages.map(function(pg){
// SET KEY HERE
pg.props.key = pg.props.title;
return pg;
}
return (
<div id="body">
<TitleBar title={title} />
<ReactCSSTransitionGroup transitionName="pg" id="transdiv" component={React.DOM.div}>
{pgs}
</ReactCSSTransitionGroup>
</div>
);
}
}
Also, if anyone can tell me the correct way to set props on unmounted components, please tell me. Setting them directly works, but it doesn't feel right.

Resources