how to receive message from BackgroundJS and change state in ReactJS and Chrome extension?

Viewed 2453

I wish to receive a message from backgroundJS of my chrome extension and change state of React DOM.

...
class App extends React.Component {
  constructor() {
    this.state = {
      message: ''
    };
  }
 func() {
   chrome.runtime.sendMessage({type:"hello"})
 }
  render() {
    return(
      <div>{this.state.message}</div>
    )
  }
}
background.js
...
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
 if (request.type == 'hello')
   chrome.runtime.sendMessage({type:'How are you'});
})

How can I get the message from backgroundJS and change this.state.message to "How are you" received?

2 Answers

sorry for being very late to the party, just want to add to jered's answer: instead of adding this.handleMessage.bind(this); inside constructor(), add this in here

componentDidMount() {
// Add listener when component mounts
    chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));
}

works for me

Related