2

Say I want to create a component that is a View, I think I'd do something like this:

class MyView extends View {
  render() { 
    return (
      <View ...>
        <Stuff />
      </View>
    );
  }
}

Now I may be unaware some very basic things here, but would it not be possible just to return the contents of my new view in render, given that the MyView will be included in some other render higher up the containment hierarchy?

So I'd like to be able to this:

class MyView extends View {
  render() {
    return (
      <Stuff />
    );
  }
}

3 Answers 3

1

You should directly return your stuff.

class MyView extends View {
    render() { return <Stuff/>; }
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's possible but a discouraged. The rule given to us by the gang of four is "favor composition" over inheritance. Composition is much more flexible.

The official React docs discuss this as well

1 Comment

I agree with the point on inheritance vs composition. Nonetheless, inheritance should not be banned altogether, it is a valid and useful technique for certain things. Here, I'd like to introduce a type of View which supports certain basic behaviour. And I thought why would I have to return another rendered View if the one doing the rendering is already a View.
0

As blockhead's answer states, inheritance is discouraged. But something similar of what you described can be achieved with composition.

You can create a base component which always, say could be a List component with different components being loaded depending on the route. Where, for example, the loading of specific data could be always done by the BaseComponent and just passing through props to the Children.

For that you would also need different containers, that call the BaseComponents containing different children components.

At the end the Containers would look this way:

<BaseComponent>
   <Children1 />
   <Children2 />
</BaseComponent>

And:

<BaseComponent>
   <Children10 />
   <Children12 />
</BaseComponent>

1 Comment

Favouring composition does not mean banishing inheritance, at least not in my book :) As I replied above, I think there's a valid role for inheritance (although composition should be used in most of the cases where inheritance used to be used). But my question was really around whether a containing component can just return it's children instead of adding another layer 'of itself' :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.