Suppose that when my React app runs, it connects to an MQTT broker where data is sent to the app. That data is then stored in an object that looks like something along these lines:
var data = {
shoeColor1: 'blue',
shoeColor2: 'red'
shoeColor3: 'orange'
}
The following React component displays that data.
import React, {Component} from 'react';
import { Button } from 'react-native';
export default class Example extends Component {
constructor(props) {
super(props)
this.state = {
buttonText: `Shoe color is ${this.props.color}`
}
}
render() {
return (
<Button title={this.state.buttonText}/>
)
}
}
and would be used like:
<Example color={data['shoeColor1']}/>
<Example color={data['shoeColor2']}/>
The data
object is going to be changing from time to time, and each time it changes, the button displaying the data should also change. I also need to keep the data
object outside of the Example component, so I can't have those changes happen internally. What I really want is for a way to update the React component whenever the data
object changes from the outside, but I'm not sure how to accomplish this. If I set state
or props
equal to something in the component and those values change externally, the component will not rerender.
These are the following steps to achieve this functionality.
If you are using state via class component then it will be like this.
<Example color={this.state.data['shoeColor2']}/>
And If you are using the useState hook then it will be the same.
<Example color={data['shoeColor2']}/>