Inheritance is a fundamental concept in object-oriented programming where a new class (subclass or derived class) can inherit properties and behaviors from an existing class (base class or parent class). In React, components can also utilize inheritance to share functionality between them.
Example
class Animal extends React.Component {
// Common properties and methods for all animals
}
class Dog extends Animal {
// Inherits properties and methods from Animal and can add its own
}
Implementing Inheritance
Implementing inheritance in React involves creating a subclass (child component) that extends a parent component. This allows the child component to reuse and build upon the functionality of the parent component.
Example
class ParentComponent extends React.Component {
// Parent component logic
}
class ChildComponent extends ParentComponent {
// Child component inherits and extends ParentComponent
}
Composition
Composition is a design principle in React where components are combined or composed to create complex UI structures. It encourages building reusable and small components that can be assembled to create larger, more sophisticated components.
Example
function Header() {
// Header component logic
}
function Footer() {
// Footer component logic
}
function App() {
return (
<div>
<Header />
{/* Other components */}
<Footer />
</div>
);
}
Composition: Using Props.children
React allows components to accept and render children's elements by utilizing the props.children property. This makes it possible to create versatile and customizable components.
When working with composition in React, child components can be organized into groups or arrays to achieve dynamic rendering of multiple items. This is especially useful for lists and collections.
React components can be composed using class components. By creating separate class components, you can encapsulate specific functionality and build complex UI structures by combining these classes.