Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find whether a React component is being displayed or not

I want to call a promise based function before dispatching an action to the store. The problem is that I only want to call the function when the component is going to be displayed. I use a toggle action that turns the component on and off.

Here is a sample of my code:

if ( /*component is going to be displayed*/) {
  init().then(function() {
    store.dispatch(toggleSomething());
  });
}
else {
  store.dispatch(toggleSomething());
}

Action:

export const SomethingActions = {
  TOGGLE_SOMETHING: 'TOGGLE_SOMETHING'
};

export function toggleSomething() {
  return {
    type: SomethingActions.TOGGLE_SOMETHING
  };
}

Reducer:

export default function somethingState(state = defaultState, action) {
  switch (action.type) {
  case somethingActions.TOGGLE_SOMETHING
    return Object.assign({}, state, { open: !state.open});

  default:
    return state;
  }
}

part of the React component:

Something.propTypes = {
  display: React.PropTypes.bool.isRequired
};

function mapStateToProps(state, ownProps) {
  return {
    display: state.something.open
  };
}

I basically want to know the value of open/display of the component above or another way to know whether the component is being displayed or not. I don't want to pollute the render function or store a bool that changes every time I call dispatch. Is there a way to do that?

like image 897
Antonios Chatzimarkos Avatar asked Feb 21 '26 20:02

Antonios Chatzimarkos


1 Answers

By the sounds of it, you'd want to take advantage of React's lifecycle methods. Particularly the componentWillMount and componentWillReceiveProps.

componentWillReceiveProps does not get triggered for the initial render, so you may want to extract out the logic into a separate function so that it can be reused for both hooks:

function trigger(isDisplayed) {
  if (isDisplayed) {
    init().then(function() {
      store.dispatch(toggleSomething());
    });
  }
  else {
    store.dispatch(toggleSomething());
  }
}

componentWillMount() {
  trigger(this.props.display);
}

componentWillReceiveProps(nextProps) {
  trigger(nextProps.display);
}
like image 182
adam-beck Avatar answered Feb 23 '26 10:02

adam-beck