Reputation: 33
I have two react components: Component1 renders a Map with MapboxGl. Component2 renders a button that when clicked, makes an API call and fetches Geojson data and stores it into a variable.
Problem: Component1 needs the Geojson data to draw a route on the map. How can I pass the the data from component2 to component1? I tried with exporting the variable from component2 and importing it in component1, but it doesn't work.
Any help would be much appreciated.
Upvotes: 2
Views: 778
Reputation: 301
In this case, I recommend using either React Context or Redux.
Here's the gist with context (it's a bit simpler imho than Redux). The example is based off this article.
import React, { createContext, useContext, useState } from 'react'
const GeoJSONContext = createContext({}) // this will be the geojson data.
const GeoJSONProvider = GeoJSONContext.Provider
const ButtonContainer = (props) => {
const { setGeoJSON } = useContext(GeoJSONContext)
return <Button onClick={() => setGeoJSON(await fetchGeoJSON())}>
Get Data
</Button>
}
const MapContainer = (props) => {
const { geoJSON } = useContext(GeoJSONContext)
return <Map data={geoJSON} />
}
const App = (props) => {
const [geoJSON, setGeoJSON] = useState([])
return (<GeoJSONProvider value={{ geoJSON, setGeoJSON }}>
<MapContainer />
<ButtonContainer />
</GeoJSONProvider>)
}
Upvotes: 1
Reputation: 442
If the 2 components that you are having are independent to each other then what you probably need is a state container such as react-redux. Wrap the 2 components in a new component and move all the data that needs to be shared in the store. Otherwise go by Wakeel's answer - props.
Upvotes: 0
Reputation: 5002
You can pass a function to the Button component as prop and call it when data is received. This means the container component hosting the map and the button component needs to keep state for the returned data. The state is then passed as property to the Map component
Upvotes: 0