mcatoen
mcatoen

Reputation: 131

Reuse everything from a React component except its render method

I have two components, one which I'd like to inherit all class functions and state from the other, but update the render method. Is there a way to do this cleanly in React?

class A extends Component {
  state = {
    ...
  }
  componentDidMount() {
    this.setState({
      ...
    });
  }
  changeText = (e) => {
    this.setState({
      text: e.target.value,
    });
  };
  changeType = (e) => {
    this.setState({
      type: e.target.value,
    });
  };
  ...
}
class B extends Component {
  render() {
    ...
  }
}

Upvotes: 3

Views: 246

Answers (2)

thecodrr
thecodrr

Reputation: 275

What you have provided should already work although you have to extend Component B from A. Like this:

class A extends React.Component {
  state = {
    text: "Hello"
  };

  componentDidMount() {
    this.setState({text: "Hello World"});
  }

  render() {
    return <h1>I am A.</h1>
  }
}

class B extends A {
  render() {
    return <h1>{this.state.text + " in B."}</h1>
  }
}

Upvotes: 1

Michalis Garganourakis
Michalis Garganourakis

Reputation: 2930

I think Higher-Order Components is what you are looking for.

HOCs are a technique in React for reusing component logic, so you can write everything you want to share in a HOC and wrap each component in need with it

Upvotes: 2

Related Questions