Reputation: 39
I have a component that runs a function and returns a result but I need the rest of my components to access that data from the function. How would I be able to do that?
Here is my app.js that contains the components. This is an example but my question is how would I run a function in Camera component and then reference the data in the Display component.
export default class App extends React.Component {
render() {
return (
<View>
<Camera />
</View>
<View>
<Display />
</View>
);
}
}
Upvotes: 1
Views: 4542
Reputation: 179
I will recommend to use redux, it simplifies stuff a lot, and do not need level up or pass state to parent/child
In your case you will need to pass props in Camera and Display component
Upvotes: 0
Reputation: 2558
If your Display component is dependant on Camera components data, I would suggest you add Display component as a child in Camera component. You can achieve this by:
e.g.
Camera component
class Camera extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
foo = () => this.setState({data: 'new_data'});
render() {
const { data } = this.state;
const dataPresent = data !== null;
return (
{
!dataPresent && (
<button value="set data" onClick={() => this.foo() />
)}
{
dataPresent && (
<Display data={data} />
)}
);
}
}
Display Component
const Display = (props) => <div> <span> { props.data } </span> </div>
If you would still like to pass/use data from one component in another component, with both components at the same level, you either need to have state for parent component or have a global store like Redux to keep data in one place and access it in Display component.
Upvotes: 0
Reputation: 11260
You can store the data as a state in the parent component and pass it as a prop to Display
, and allow Camera
to alter the state through a callback (setData
in the example below).
export default class App extends React.Component {
state = {
data: null,
};
render() {
return (
<View>
<View>
<Camera setData={(data) => this.setState({ data })} />
</View>
<View>
<Display data={this.state.data} />
</View>
</View>
);
}
}
const Camera = props => <Button onPress={() => props.setData(...)} />
const Display = props => <Text>{props.data}</Text>
Upvotes: 1