ButuzGOL
ButuzGOL

Reputation: 1243

Get component from react relay Container

How can I get Component from React Relay Container to get static variable ?

import Home from './pages/home';

console.log(Home.route) // undefined

I need something like Home.Component.route // object

class Home extends React.Component {
  static route = {
    component: Home,
    route: HomeRoute,
    leftButton: false,
    sideMenu: false,
  };

  render() {
    return (
      <View style={styles.container}>
        <Text>
          Home
        </Text>
        <Text>
            {this.props.greetings.hello}
        </Text>
      </View>
    );
  }
}

export default Relay.createContainer(Home, {
  fragments: {
    greetings: () => Relay.QL`
      fragment on Greetings {
        hello,
      }
    `,
  }
});

Upvotes: 1

Views: 510

Answers (1)

Greg Hurrell
Greg Hurrell

Reputation: 5437

I don't think there's a way to get at this statically without doing one of the following.

Alternative 1: Add an explicit export of the wrapped component

// In "Home.js":
export class HomeComponent extends React.Component {
  static route = {
    // ...
  }
}

export default Relay.createContainer(HomeComponent, {
  // ...
});

// In "Other.js":
import Home, {HomeComponent} from './Home.js';

console.log("should have access here", HomeComponent.route);

Alternative 2: Add properties to the container before exporting

const HomeContainer = Relay.createContainer(
  // ...
);

HomeContainer.route = {
  // ...
};

export default HomeContainer;

Alternative 3: Access via refs at runtime

Once the container is mounted and you have a reference to it you can get at the original component via the "component" ref. Note that this is not documented and therefore not guaranteed to work in the future.

// In "Other.js":
render() {
  return (
    <Home
      ref={
        container => (
          console.log(container.refs.component.route)
        )
      }
    />
  );
}

Obviously, this is the hackiest of the three alternatives, so I probably wouldn't recommend it.

Upvotes: 3

Related Questions