Skip to content
Advertisement

Access Class Instance Props in React Component?

I have a class that only returns the children only

class Name extends PureComponent {
  constructor(props) {
   super(props);
   this.text = "meow";
  }
  render() {
    return this.props.children;
  }
}

And I created the Component in my JSX with text saying my Classes Prop “text”

<Name>
  <Text>{Name.text}</Text>
</Name>

But it errors saying that Name.text doesn’t exist, Did you mean to access a static property?

How do I use the JSX tag just to do new Name() then access the info inside using React/React Native?

Edit 1 Better Example

interface User {
  data: object;
  firstName: string;
  lastName: string;
}
class User extends PureComponent {
  constructor(props: object) {
    super(props);
    fetch("https://randomuser.me/api/")
      .then((response) => response.json())
      .then((data) => this.data);
    this.firstName = this.data.results.name.first;
    this.lastName = this.data.results.name.last;
  }
  render() {
    return this.props.children;
  }
}
<User>
  <Text>{User.firstName}</Text>
</User>

Advertisement

Answer

If you want the User component to have the logic for figuring out the first name and last name, but you want the parent component to decide what to do with those values, then I’d recommend using a render prop. This lets you pass a function to Name, telling it what you would like to render.

Here’s an example passing the function as the children prop (though you could use a different prop if you prefer):

class User extends PureComponent {
  state = {
    firstName: '',
    lastName: '',
  }
  constructor(props: object) {
    super(props);
    fetch("https://randomuser.me/api/")
      .then((response) => response.json())
      .then((data) => {
        this.setState({ 
          firstName: data.results.name.first, 
          lastName: data.results.name.last,
        });
      });
  }
  render() {
    return this.props.children(this.state.firstName, this.state.lastName);
  }
}

// used like:

<User>
  {(firstName, lastName) => (
    <Text>{firstName}</Text>
  )}
</User>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement