0

In my React Native app I have a class component Parent and in it I define two functional components ChildA and ChildB. This works without errors:

class Parent extends Component {
  const ChildA = () => {
    return <View a={this.props.a} b={this.props.b} c={101}/>
  }
  const ChildB = () => {
    return <View a={this.props.a} b={this.props.b} c={102}/>
  }
}

I want to modularize this by creating GenericChild like this:

class Parent extends Component {
  const GenericChild = (props) => {
    return <View a={this.props.a} b={this.props.b} c={props.c}/>
  }
  const ChildA = () => {
    return <GenericChild c={101}/>
  }
  const ChildB = () => {
    return <GenericChild c={102}/>
  }
}

This throws the error Cannot read properties of undefined (reading 'apply').

What did I do wrong?

gkeenley
  • 6,088
  • 8
  • 54
  • 129

1 Answers1

0

Unless there are specific needs that require ChildA and ChildB to be a part of Parent, the former shouldn't be defined as an instance method of the latter. Also, class members/properties/variables cannot have the const keyword

A better approach would be simply to create two separate components and pass the props needed, e.g.

const GenericChild = (props) => {
  return <View a={props.a} b={props.b} c={props.c} />;
};

export class Parent extends React.Component {
  render() {
    return (
      <>
        <GenericChild a={this.props.a} b={this.props.b} c={101} />
        <GenericChild a={this.props.a} b={this.props.b} c={102} />
      </>
    );
  }
}
klundn
  • 46
  • 2