I have a variable called brands
which is a list. Under return
in render
, when I try to map over the list and create new paragraph tag, I get this error: Expected to return a value in arrow function array-callback-return
.
var brands = [];
ponentDidMount(){
database.ref("/brands/").on('child_added', (snapshot)=>{
var data = snapshot.val();
console.log(data);
brands.push(data);
})
}
render(){
return(
<div>
{brands.map((brand)=>{
<p>{brand}</p>
}
)}
</div>
)
}
I have a variable called brands
which is a list. Under return
in render
, when I try to map over the list and create new paragraph tag, I get this error: Expected to return a value in arrow function array-callback-return
.
var brands = [];
ponentDidMount(){
database.ref("/brands/").on('child_added', (snapshot)=>{
var data = snapshot.val();
console.log(data);
brands.push(data);
})
}
render(){
return(
<div>
{brands.map((brand)=>{
<p>{brand}</p>
}
)}
</div>
)
}
Share
Improve this question
edited Jun 15, 2019 at 16:46
Kalle Richter
8,78729 gold badges93 silver badges207 bronze badges
asked Jul 12, 2018 at 12:30
VedantVedant
3072 gold badges5 silver badges13 bronze badges
1
-
You might want to put
brands
in state. Since it won't re-render the ponent until the state has been changed. – Manoz Commented Jul 12, 2018 at 12:49
3 Answers
Reset to default 6Add a return
statement to your arrow function and it will work as expected:
render() {
return(
<div>
{brands.map((brand) => {
return <p>{brand}</p>;
})}
</div>
)
}
You could also change {}
to ()
to get an implicit return:
render() {
return(
<div>
{brands.map((brand) => (
<p>{brand}</p>
))}
</div>
)
}
You also have to put your brands
in state so the ponent will re-render when brands
update. Make sure not to push to the array, since that will mutate it.
Example
class App extends React.Component {
state = { brands: [] };
ponentDidMount() {
database.ref("/brands/").on("child_added", snapshot => {
var data = snapshot.val();
this.setState(previousState => {
return { brands: [...previousState.brands, data] };
});
});
}
render() {
return (
<div>
{this.state.brands.map((brand, index) => (
<p key={index}>{brand}</p>;
))}
</div>
);
}
}
You may also drop the braces like this:
{ brands.map(brand => <p>{brand}</p>) }
i suggest to use function and return, and use state to store your brands
import _ from 'lodash';
constructor() {
super();
this.state = {
brands: []
}
}
ponentDidMount(){
let newData = [];
database.ref("/brands/").on('child_added', (snapshot)=>{
let data = snapshot.val();
console.log(data);
newData.push(data);
});
this.setState({
brands: newData
});
}
renderBrand = () => {
return _.map(this.state.brands, (brand, i) => {
return <p>{brand}</p>;
});
}
render(){
return(
<div>
{ this.renderBrand() }
</div>
)
}