Everything you need as a full stack developer

React Render Props with shared component logic

- Posted in React by

TL;DR Render props allow you to share component logic without duplicating code by passing functions as props. This technique enables reusability of complex logic across multiple components, making code more maintainable, efficient, and scalable.

Render Props with Shared Component Logic: Unleashing React's Power

As a seasoned Fullstack Developer, you're no stranger to building complex user interfaces using React. One of the library's most powerful features is its ability to share component logic through render props. In this article, we'll dive into the world of render props and explore how they can help you write more maintainable, efficient, and scalable code.

What are Render Props?

Render props are a technique in React that allows us to pass a function as a prop to a component. This function is then called within the component's render method, allowing it to return JSX elements or other values. The key benefit of render props is that they enable us to share complex logic between components without having to duplicate code.

A Simple Example

Let's start with a simple example to illustrate the concept. Suppose we have a LoadingIndicator component that displays a loading animation while data is being fetched from an API.

import React, { Component } from 'react';

class LoadingIndicator extends Component {
  render() {
    return (
      <div className="loading-indicator">
        <img src="loading.gif" alt="Loading..." />
      </div>
    );
  }
}

Now, let's say we want to display this loading indicator in multiple places throughout our app. We could duplicate the LoadingIndicator component, but that would be inefficient and hard to maintain. Instead, we can create a higher-order component (HOC) that wraps the LoadingIndicator with render props.

import React from 'react';

const withLoadingIndicator = (WrappedComponent) => {
  return function EnhancedComponent(props) {
    const isLoading = props.isLoading;

    if (isLoading) {
      return <LoadingIndicator />;
    }

    return <WrappedComponent {...props} />;
  };
};

export default withLoadingIndicator;

With this HOC, we can now wrap any component with the withLoadingIndicator prop and pass in the isLoading boolean value. The HOC will render the LoadingIndicator component if the condition is true.

import React from 'react';
import withLoadingIndicator from './withLoadingIndicator';

const MyComponent = () => {
  const isLoading = true; // or false

  return (
    <div>
      <h1>My Component</h1>
      {withLoadingIndicator(LoadingIndicator)({
        isLoading,
      })}
    </div>
  );
};

Sharing Logic with Render Props

Render props allow us to share logic between components in a more elegant way. By passing a function as a prop, we can reuse complex logic without duplicating code. Let's take the example of a DataGrid component that fetches data from an API and displays it in a table.

import React, { useState, useEffect } from 'react';

const DataGrid = ({ url, columns }) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => setError(error))
      .finally(() => setLoading(false));
  }, [url]);

  return (
    <div>
      {loading ? (
        <LoadingIndicator />
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        <table>
          <thead>
            <tr>
              {columns.map((column, index) => (
                <th key={index}>{column.header}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.map((row, index) => (
              <tr key={index}>
                {columns.map((column, columnIndex) => (
                  <td key={columnIndex}>{row[column.key]}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
};

Now, let's say we want to create a Table component that wraps the DataGrid with render props. We can use the same HOC from earlier and pass in the data, error, and loading state values as props.

const Table = ({ data, error, loading }) => {
  return (
    <div>
      {loading ? (
        <LoadingIndicator />
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        <table>
          {/* render table here */}
        </table>
      )}
    </div>
  );
};

const TableWithData = withLoadingIndicator(Table);

By using render props, we can share the logic between components and keep our code DRY (Don't Repeat Yourself).

Conclusion

Render props are a powerful technique in React that allows us to share component logic without duplicating code. By passing functions as props, we can reuse complex logic across multiple components, making our code more maintainable, efficient, and scalable. In this article, we explored how render props can be used with shared component logic and saw examples of how to use them in practice. Whether you're building a simple app or a complex enterprise-level system, render props are an essential tool in your React developer toolkit.

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more