Search code examples
javascriptreactjsreact-nativereact-propsreact-component

Updating React Component When Outside Data Changes


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.


Solution

  • These are the following steps to achieve this functionality.

    1. In parent component create an object of the state. Which will hold the initial state of the colors.
    2. Now when the MQTT send the data to your client app, set the state with newer object.
    3. Pass that state object to the Example component.

    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']}/>