ctrlplusb / react-component-queries

Provide props to your React Components based on their Width and/or Height.
MIT License
183 stars 12 forks source link

Question: how to access assigned props from parent or other elements #78

Open mx781 opened 7 years ago

mx781 commented 7 years ago

First of, thanks for creating this -- seems a very promising tool for complex, responsive layouts.

I am trying to access the assigned props to components from a parent, but can't seem to find where in the Component Object they are stored, or what to call to retrieve them.

Consider this example:

import React, { Component } from 'react';
import componentQueries from 'react-component-queries';

class Expander extends Component {
  constructor(props) {
    super(props);
    this.state = { text: props.text };
    this.interval = setInterval(() => this.tick(), 1000);
  }

  tick() {
    this.setState({
      text: this.state.text += " is foo"
    });
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <button>
        {this.state.text}
        ({this.props.widthOver100 ? "LARGE" : "small"})
      </button>
    );
  }
}

const AwareExpander = componentQueries(
  ({ width }) => ({ widthOver100: width > 100 })
)(Expander);

class Container extends Component
{
  render()
  {
    console.log(this.props.children)
    return (
      <div>{this.props.children}</div>
    )
  }
}

export class App extends Component {
  render() {
    return (
      <Container>
        <AwareExpander text="bar" />
      </Container>
    );
  }
}

(apologies for lack of live example -- I tried putting it into WebpackBin, but couldn't get it to work)

Is there a way to access the newly set props (or even just width/height) of a child (AwareExpander) from a parent component, in this case Container, preferably in the render() method?