leshow leshow - 2 months ago 7
React JSX Question

react - function in component body

I saw this code in a tweet and I don't understand how OnScreenResize is implemented such that width/height are supplied as arguments. I'm not assuming a familiarity with these components, particularly I'd just like to see how it might be implemented. i.e. how the children as a function is called and passed values

const LeftIcon = ({ onDrawerToggle }) => (
<OnScreenResize debounce={50} bounds={[400,500]}>
{({ width, height }) =>
width > smallTablet.value
? Component(onDrawerToggle)
: OtherComponent()}
</OnScreenResize>
)

Answer

This is how OnScreenResize can be implemented:

class OnScreenResize extends Component {
  constructor(props) {
    super(props);
    this.state = {
      width: 0,
      height: 0    
    };
    this.updateWidthAndHeight = this.updateWidthAndHeight.bind(this);
  }

  componentWillMount() {
    this.updateWidthAndHeight();
    window.addEventListener('resize', this.updateWidthAndHeight);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWidthAndHeight);
  }

  updateWidthAndHeight() {
    this.setState({
      width: window.innerWidth,
      height: window.innerHeight
    });
  }

  render() {
    const { width, height } = this.state;
    return this.props.children({ width, height });
  }
}