This question already has an answer here:
Can't iterate over my array/object. Javascript, React Native [duplicate]
(1 answer)
Closed 5 years ago.
I have an array prop on a component called jobs that will show in the console, but always returns length:0
The Image you will see definitely has three elements in the array, but when I attempt to access the array length through console.log(this.props.jobs.length);
Why do the elements of this array log out, but I can't access the elements in code?
Per request from #finalfreq, see full code below:
const DepartmentContainer = React.createClass({
getInitialState:function(){
return{sortedJobs:{}, loaded:false};
},
componentDidMount:function(){
//console.log(this.state.sortedJobs);
var departments = this.props.departments;
departments.map(function(name, index){
this.state.sortedJobs[name] = [];
}, this)
var _this = this;
axios.get('{api call returning json}')
.then(function (response) {
for(let i=0;i<response.data.jobs.length;i++){
for(let j=0;j<response.data.jobs[i].metadata[0].value.length;j++){
_this.state.sortedJobs[response.data.jobs[i].metadata[0].value[j]].push(response.data.jobs[i]);
}
}
})
.catch(function (error) {
console.log(error);
});
//console.log(Object.keys(_this.state.sortedJobs).length);
this.setState({sortedJobs: _this.state.sortedJobs});
this.setState({loaded:true});
},
render:function(){
var departments = this.state.sortedJobs;
return(
<div>
{this.state.loaded ?
<div className="row grid-12">
{Object.keys(departments).map(function(label, department){
//console.log(departments[label]);
return <Department key={label} title={label} jobs={departments[label]}/>
})}
</div>
:
<div>Test</div>
}
</div>
);
}
});
const Department = React.createClass({
getInitialState:function(){
return{hidden:false, hasJobs:false};
},
componentWillMount:function(){
const jobs = this.props.jobs;
if(jobs.length>0){
this.setState({hasJobs:true});
}
},
componentDidMount:function(){
console.log(this.state.hasJobs);
console.log(this.props.jobs.length);
},
renderNormal:function(){
return(
<div className="grid-4 department-block" data-dep-filter={this.state.hidden} data-loc-filter="false" data-department={this.props.title}><h3 className="text-uppercase">{this.props.title}</h3>
<div className="posting-list margin-bottom">
<h3 className="text-uppercase">{this.props.title}</h3>
</div>
</div>
)
},
renderEmpty:function(){
return(
<div className="grid-4 department-block" data-dep-filter={this.state.hidden} data-loc-filter="false" data-department={this.props.title}><h3 class="text-uppercase">{this.props.title}</h3>
<div className="posting-list margin-bottom">
<div class="no-posts job-post">
<p><em>0 Current Openings</em></p>
</div>
</div>
</div>
);
},
render: function(e){
if (this.hasJobs) {
return (
this.renderNormal()
)
}else{
return(
this.renderEmpty()
)
}
}
});
In the Department:componentWillMount function I want to check the jobs array passed to it from the DepartmentContainer:render function and set the state on said Department to either hasJobs true/false
#finalfreq has the right idea. This is an artifact of how the JavaScript console works (for Chrome at least). Values are generally only displayed/retrieved when you expand them, which can lead to some counter intuitive behavior. You must be adding elements to the array after you are logging it to the console.
Check it out:
I make an array and push something into it. Then I log it to console. Then I push a second element.
Now when I expand the previous logged Array, you'll see it now has the most up-to-date values. Except "Array[1]" doesn't update to "Array[2]"... and if you push another value into the array, the previously logged values won't change even if you collapse and expand them again.
The moral of the story is... don't rely on console.log too much hehe. But if you do, learn its quirks.
Related
I made a list of product which contains name, price etc.. properties. Then I created a simple search box and I am searching my products based on product name . the search result returns the correct object but the UI is not getting updated with that result.Initially, I am able to see the list but after searching it is not getting updated. I am new to react SO need some help. here is my code
OnInputChange(term)
{
let result= this.products.filter(product=>{
return product.name==term;
});
console.log(result);
let list=result.map((product)=>
{
return <li key={product.price}>{product.name}</li>
});
console.log(list);
this.setState({listOfProducts:list});
}
render()
{
this.state.listOfProducts=this.products.map((product)=>
{
return <li key={product.price}>{product.name}</li>
});
return <div>
<input onChange={event=>{this.OnInputChange(event.target.value)}}/>
<ul>{this.state.listOfProducts}</ul>
</div>
}
}`
this.products.filter should probably be this.state.products.filter
When referring to a Components method you say this.onInputChange but when referencing state you must say this.state.products because this.products doesn't exist.
I would also move this:
let list=result.map((product)=>
{
return <li key={product.price}>{product.name}</li>
});
to your render statement. so your onchange handler could be:
OnInputChange(term)
{
let result= this.products.filter(product=>{
return product.name==term;
});
this.setState({listOfProducts:result});
}
and then you
render(){
return(
{this.state.listOfProducts.map(product => {
return <li key={product.price}>{product.name}</li>
})}
)
}
hope that helps! If your problem persists please share your entire code so I can better understand the issue.
I don't think I fully understand how the Parent/Child relationship works in React. I have two components, Column and Space. When a Column is rendered, it creates some Spaces. I thought that meant that the Column would be the parent to those Spaces, but either I'm wrong or I'm using some part of React.Children.count(this.props.children) incorrectly - it always tells me that any given Column has 0 children.
Simplified models:
var Column = React.createClass({
getInitialState: function() {
return {childCount: '', magicNumber: this.props.magicNumber};
},
componentDidMount: function() {
var newCount = React.Children.count(this.props.children);
this.setState({childCount: newCount});
},
render: function() {
return (
<div className='Column'>
{
Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>)
}
</div>
);
}
});
var Space = React.createClass({
render: function() {
return (
<div className="Space">
space here
</div>
);
}
});
It seems like no matter where I put React.children.count(this.props.children) in a Column, it tells me there are 0 children. I would expect the Column generated in the example code to have five children, since five Spaces are created within it.
I figured maybe I was trying to count the Children before they were fully loaded, so I tried writing a click handler like this:
//in Column
setChildCount: function () {
var newCount = React.Children.count(this.props.children);
this.setState({childCount: newCount});
}
Then adding a button like this in my Column:
...
render: function() {
return (
<div className='Column'>
{
Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>)
}
<button onClick={this.setChildCount} />
{this.state.childCount}
</div>
);
But my childCount is always and forever 0. Can anyone see where I'm going wrong?
Edit: Ultimately, I want to get a count of all children elements who have X attribute in their state set to Y value, but I am clearly a step or three away from that.
The Column component doesn't have any children on that code. Childrens are components which are wrapped by the parent component. So imagine:
<Column>
<Space/>
<Space/>
<Column/>
In this case the parent Column has two children Space
On your code:
<div className='Column'>
{
Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>)
}
</div>
You are creating new components inside a divnot inside the component Column
You are rendering Space components as part of the Column component. The parent/child relationship captured by this.props.children looks like this:
var Column = React.createClass({
render: function() {
<div className="column">
{this.props.children}
</div>
}
});
ReactDOM.render(
<Column>
<Space /> //little space children
<Space />
</Column>
);
To get at your specific problem, you don't need anything like this.props.children because you have everything right there in your render method.
So the answer to your question is: apply the same logic as when you render them.
Why is it not possible to access this.state.board within componentDidMount? As I understand it, once the component has been rendered, componentDidMount is fired immediately after, and only once.
I am trying to set up a Google Analytics ecommerce tracker, and so I thought the best place to set that up would be within the componentDidMount because it ensures that the GA tracker is called only once. However, I am not able to access any of the state data to send back to GA. Any ideas?
//function which establishes state
function getEditorState() {
var board = Editor.getCsb();
var similarBoard = Editor.getSimilarLsbs();
return {
board: board,
similarBoard: similarBoard,
editing: Editor.isEditing(),
hoverColor: Editor.getHoverColor(),
variant: Editor.variant(),
lidAndLsb: Editor.getLidAndLsb()
};
}
//component
var CsbEditorApp = React.createClass({
getInitialState: function () {
return getEditorState();
},
componentDidMount: function () {
console.log(this.state.board); // <---- this returns an empty object.
Editor.addChangeListener(this._onChange);
SbAction.loadCsb(this.props.params.cid);
},
render: function() {
console.log(this.state.board); // <---- this returns the the board object with data.
return (
<div className={cm('lightbox sb-bg overlay-border')} ref="app">
<Header board={this.state.board} label={this.state.label} socialLinkStatus={this.state.socialLinkStatus} buyingAll={this.state.buyingAll} />
<div className="viewer-content">
<div id="csb-content">
<MetaText className="meta-author" metaKey="author" board={this.state.board} />
<BoardMeta board={this.state.board}/>
<CsbPanel board={this.state.board hoverColor={this.state.hoverColor} showPanel={showPanel} />
<RouteHandler/>
</div>
</div>
</div>
);
},
_onChange: function () {
this.setState(getEditorState());
$("#cc_hover").hide();
}
});
console.log is not a reliable method of debugging - the method is async and actually can get called after you've set up your listener or even after the callback it registers (which affects the state) has been triggered, so use the debugger. Also, try commenting out the Editor.addChangeListener(this._onChange); line and see if it causes the problem.
I'm learning Reactjs and tried to copy the example from this facebook git, children to make the warning disappear, but I'm still getting it:
var MyComponent = React.createClass({
getInitialState: function () {
return {idx: 0};
},
render: function() {
var results = this.props.results;
return (
<ol>
{results.map(function(result) {
return <li key={result.id}>{result.book}</li>;
})}
</ol>
);
}
});
var result = [
{title: "book", content: "booky"},
{title: "pen", content: "penny"},
];
document.addEventListener("DOMContentLoaded", function () {
ReactDOM.render(<MyComponent results={results} />, document.getElementById('widgets'));
});
A few things going on here that need to be rectified:
The variable you're declaring and assigning the array of results to is named result but you are passing a variable named results as the results prop to MyComponent. Rename this variable to results.
The two object properties you're attempting to access on the result object inside the map function are id and book, neither of which are defined on the object itself (title and content are). Change {result.book} to {result.title} in this case.
Finally, in order to supply a unique ID to each element returned from the map, set the second parameter of your map (e.g. results.map(function(result, i) {... and use the array index as your unique key.
In summary:
results.map(function(result, i) {
return <li key={i}>{result.title}</li>;
})
I'm a beginner of ReactJS and I'm stuck trying to figure out why map only returns a single prop at a time.
In file1.jsx, I have an array that contains 3 objects:
var MainPanelOneData = [{"id":1,"shotviews":15080},{"id":2,"likes":12000},{"id":3,"comments":5100}];
File1.jsx also has a render function to extrapolate the data inside the array:
render: function() {
var ListMainPanelOne = MainPanelOneData.map(function(data) {
return <MainPanelOne key={data.key} shotviews={data.shotviews} likes={data.likes} comments={data.comments} />
});
In file2.jsx, I have this code to render the data object from file1.jsx:
render: function() {
return (
<div>
<span>{this.props.shotviews} shot views</span>
<span>{this.props.likes} likes</span>
<span>{this.props.comments} comments</span>
</div>
)
}
The result shows this:
15080 shot views likes comments
shot views12000 likes comments
shot views likes5100 comments
I'm guessing it repeats like this because it searches through one key at a time? If that's the case, how do I display all keys at the same time? Use indexing?
well your array of data doesnt have all the keys. each one of your objects in PanelOneData has ONE key and is missing the other two; additionally none of them have key called key. so youre making three MainPanelOne components, each with a single prop. the result of that map is this
[
<MainPanelOne key={null} shotviews={15080} likes={null} comments={null} />,
<MainPanelOne key={null} shotviews={null} likes={12000} comments={null} />,
<MainPanelOne key={null} shotviews={null} likes={null} comments={5100} />
]
which is an accurate display of what youre seeing
To get one line you might do something like this.
render: function() {
var ListMainPanelOne = MainPanelOneData.map(function(data) {
return <span key={data.id}> {data.shotviews} {data.likes} {data.comments} </span>
});