If I make a variable inside a react component, how do I re-access it on a state change?

Chris picture Chris · Jun 28, 2016 · Viewed 7.6k times · Source

I am making a react project and using wavesurfer.js. When I hit a play button I change the prop playing from false to true, the method used to make the element actually play is visual.playPause(); however, I'm not sure how I would get a reference back to the variable after I created it (the variable being visual which was created inside the initWaveSurfer function). Any help would be amazing!!

var React = require('react');
var ReactDom = require('react-dom');

var reactWaveSurfer = React.createClass({
  getInitialState: function(){
    return ({
      song: this.props.song,
      playing: this.props.playing
    });
  },
  componentDidMount: function () {
    this.initWavesurfer();
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      playing: nextProps.playing
    });
  },
  initWavesurfer: function () {
    var visualContainer = ReactDom.findDOMNode(this.refs.waveContainer);
    var visual = WaveSurfer.create({
      container: visualContainer,
      waveColor: 'blue',
      progressColor: 'purple',
      barWidth: '3',
      height: "90",
      maxCanvasWidth: 200
    });
    visual.load(this.state.song.audio_url);
  },
  render: function () {
    return <div className="wave-surfer" ref="waveContainer" ></div>;
  }
});

module.exports = reactWaveSurfer;

Answer

Bwaxxlo picture Bwaxxlo · Jun 28, 2016

You can access it by returning it from this.initWavesurfer and setting your state from that. From there, you can access it thru this.state.visual;

var React = require('react');
var ReactDom = require('react-dom');

var reactWaveSurfer = React.createClass({
  getInitialState: function(){
    return ({
      song: this.props.song,
      playing: this.props.playing
    });
  },
  componentDidMount: function () {
    this.setState({visual: this.initWavesurfer()}); //You now have access to visual thru this.state.visual
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      playing: nextProps.playing
    });
  },
  initWavesurfer: function () {
    var visualContainer = ReactDom.findDOMNode(this.refs.waveContainer);
    var visual = WaveSurfer.create({
      container: visualContainer,
      waveColor: 'blue',
      progressColor: 'purple',
      barWidth: '3',
      height: "90",
      maxCanvasWidth: 200
    });
    visual.load(this.state.song.audio_url);
    return visual;
  },
  render: function () {
    return <div className="wave-surfer" ref="waveContainer" ></div>;
  }
});

module.exports = reactWaveSurfer;