c-poulsen c-poulsen - 26 days ago 7
Javascript Question

Using props in react

Im building an app with data from an api and i want to include the users latitude and longitude in the app.

My app is in two files:

app.js
and
main.js


In
app.js
i render the component like this:

render(<Main source="https://api.darksky.net/forecast/apikey/latitude,longitude?units=auto"/>, document.getElementById('app'));


The latitude and longitude is currently hardcoded in the component source, and i want to make these dynamic.

In my
main.js
the component uses the api like this:

componentDidMount() {
this.serverRequest = $.get(this.props.source, function (result) {
this.setState({
daily: result.daily.data,
hourly: result.hourly.data
});
}.bind(this));
}


Im able to fetch the users location using HTML geolocation - which i guess i should store in the constructor or componentWillMount, but i need a way to send the variable into the
app.js
file in the source for the main component - i guess i should use props like for the source but i dont know how

Answer

It may be a good approach to pass the longitude and latitude into your component as props and to assemble the URL inside the component:

render(<Main longitude={longitude} latitude={latitude} />, document.getElementById('app'));

componentDidMount() {
    const url = `https://api.darksky.net/forecast/apikey/${this.props.latitude},${this.props.longitude}?units=auto`;
    this.serverRequest = $.get(url, function (result) {
        this.setState({
            daily: result.daily.data,
            hourly: result.hourly.data
        });
    }.bind(this));
}