Component composition
As was mentioned earlier in this chapter, React favors composition over inheritance. What does this mean? In essence, it means to build complex or derivative components, instead of using something akin to object-oriented inheritance, we use composition to build up complexity from simple building blocks.
Our Title
component is pretty simple, but we can build up a more complex NewsItem
component from the Title
component and other simple components:
import React, { Component } from 'react'; class NewsItem extends Component { render() { return ( <div className="news-item"> <Image /> <Title /> <Byline /> <Description /> </div> ); } }
The JSX returned by the render method of a component is that component's declarative definition. When that JSX includes other components, such as the <Image />
, <Title />
, <Byline />
, and <Description />
elements we see in the preceding code, it is said to be composed of those components.
Composition has other uses besides making increasingly more complex components from smaller, simpler building blocks. Composition can also be used to make derivative components, a task that in an object-oriented programming world we might use inheritance to achieve. For instance, imagine we want to make a component that is a WarningTitle
. This component might share many properties with a Title
component, but also add bright red border around it in order to draw a user's attention:
import React, { Component } from 'react'; class WarningTitle extends Component { render() { return ( <div style={{ border: '1px solid red' }}> <Title /> </div> ); } }
Using the previous definition, we would then say that WarningTitle
is composed of Title
because the latter is returned in the render()
method of the former.