Reputation: 11485
I have some records in the firebase, this code is to fetch it and put the result to a subcomponent. Here's the code
import React from "react";
export default class Home extends React.Component{
componentWillMount(){
this.firebaseRef = new Firebase('https://sweltering-heat-7923.firebaseio.com/contact');
this.firebaseRef.once("value", function (snapshot){
snapshot.forEach(function(data){
console.log(data.val());
});
});
}
render(){
return(
<List />
)
}
}
class List extends React.Component{
render(){
return(
<div class="row">
// populate props from Home component
</div>
)
}
}
What I don't how to do is passing the response data to sub component which is List in this case.
And the firebase data look like this:
object {
id:12131323,
firstName:'john',
address: {steet:'some street', city:'havana'}
}
object {
id:12221232,
firstName:'joe',
address:{steet:'big street', city:'dubai'}
}
Upvotes: 0
Views: 1771
Reputation: 2644
I think you're looking for populating that list with some items. slight modifications of your code:
class Home extends React.Component{
constructor(props) {
super(props);
this.state = {
items: [],
}
/// must set initial state, because this is being passed as a prop
}
componentWillMount(){
const self = this;
const url = 'https://sweltering-heat-7923.firebaseio.com/contact';
this.firebaseRef = new Firebase(url);
this.firebaseRef.once("value", function (snapshot){
// update state with new items
// which will cause re-rendering of <List> with the new items.
snapshot.forEach(function(data){
self.setState({
items: self.state.items.concat(data.val())
})
});
});
}
render(){
return(
<List items = { this.state.items } />
)
}
}
and List would look something like this:
const List = (props) => {
return (
<ul>
{ props.items.map( (item,i) => {
const { firstName, id } = item;
const address = item.address.street + ', ' + item.address.city;
return (
<li key = { i } >
<div>{ id }</div>
<div> { name } </div>
<div> { address} </div>
</li>
)
})}
</ul>
)
}
what happens here is:
1) setting initial state of app with an empty array called items
2) updating state with new items by adding them to the items
array
3) passing the items
array to the List component, as a value to a prop called items
<List items = { items } />
,
4) mapping over the value of the prop items
to render the actual items.
Hope this helps!
Upvotes: 3