I want to declare a global variable inside of a function and then use it outside the function. I have tried putting the JSX inside of the function so I can easily access it but that doesn't work because the renderer returns null.
APP.JS:
class App extends React.Component {
render() {
firebase
.database()
.ref()
.limitToLast(1)
.on('child_added', function (childSnapshot) {
var snap = childSnapshot.val();
var category = snap.category;
var condition = snap.condition;
var postname = snap.postname;
var postprice = snap.postprice;
var username = snap.username;
var usernumber = snap.usernumber;
var imageURL = snap.imageURL;
var postdescription = snap.postdescription;
var whatsapplink = 'https://wa.me/' + usernumber + '?text=';
});
return (
<>
<div></div>
<div style={{float: 'left'}}>
<Ads
imageURL={imageURL}
name={postname}
price={postprice}
category={category}
condition={condition}
description={postdescription}
username={username}
usernumber={usernumber}
whatsapplink={whatsapplink}
/>
</div>
</>
);
}
}
export default App;
Should I write a function to get data from firebase in the render?
ADS.JS:
import React from 'react';
import '../App.css';
class ads extends React.Component {
render() {
return (
<div>
<img src={this.props.image} alt="image"></img>
<h2>{this.props.name}</h2>
<h2>{this.props.price}</h2>
<h2>{this.props.category}</h2>
<h2>{this.props.condition}</h2>
<h2>{this.props.description}</h2>
<h2>{this.props.username}</h2>
<a href={this.props.whatsapplink}>
<button>Chat with Seller</button>
</a>
</div>
);
}
}
export default ads;
I want to declare a global variable inside of a function and then use it outside the function. Hint: DON'T, this is not how react was meant to be used. What you want to do is to pass it as an argument to your components viaprops. Make sure you life state up to a common ancestor component.