Passing Values Between Parent and Child Components in Next.js

In a typical React (or Next.js) application, communication between parent and child components is essential for building dynamic UIs. The most common ways to pass data between components involve using props (to send data from parent to child), state management (to send data from child to parent), and sometimes context when data needs to be shared across many components. In this blog post, we’ll explore how to pass values between parent and child components in Next.js, as well as some best practices to ensure clean and maintainable code.

Passing Values from Parent to Child: Using Props

The most straightforward way to pass data from a parent component to a child component is through props. Props allow you to send values to child components and render them dynamically. This is a fundamental concept in React and is widely used in Next.js applications.

Example:

// Parent Component
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const message = "Hello from Parent!";
  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent message={message} />
    </div>
  );
};

export default ParentComponent;

// Child Component
const ChildComponent = ({ message }: { message: string }) => {
  return <p>{message}</p>;
};

export default ChildComponent;

In the above example:

  • The ParentComponent passes the message variable to ChildComponent using props.
  • The ChildComponent receives the message prop and displays it.

Passing Values from Child to Parent: State + Callback

Passing data from a child component to a parent requires a different approach, as React follows a unidirectional data flow. In this case, we use a callback function passed down from the parent to the child. The child can then call this function to send data back to the parent component.

Example:

// Parent Component
import { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [childData, setChildData] = useState<string>('');

  const handleChildData = (data: string) => {
    setChildData(data);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <p>Received from Child: {childData}</p>
      <ChildComponent onDataChange={handleChildData} />
    </div>
  );
};

export default ParentComponent;

// Child Component
import { useState } from 'react';

const ChildComponent = ({ onDataChange }: { onDataChange: (data: string) => void }) => {
  const [inputValue, setInputValue] = useState<string>('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
    onDataChange(e.target.value); // Pass data back to parent
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Type something"
      />
    </div>
  );
};

export default ChildComponent;

Here:

  • ParentComponent defines a state (childData) and a function (handleChildData) to update it.
  • The parent passes handleChildData as a prop (onDataChange) to ChildComponent.
  • ChildComponent calls the onDataChange function whenever the input value changes, thus sending data back to the parent.

Using Context for Shared State (Optional)

For more complex applications where data needs to be shared across deeply nested components, React Context can be used. It allows components to access shared state without the need to pass props through every level of the component tree. This is especially useful when multiple components need to consume and update the same data.

Example:

// context.tsx
import { createContext, useContext, useState, ReactNode } from 'react';

interface AppContextType {
  message: string;
  setMessage: (message: string) => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

export const AppProvider = ({ children }: { children: ReactNode }) => {
  const [message, setMessage] = useState<string>('Hello from Context!');
  
  return (
    <AppContext.Provider value={{ message, setMessage }}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppContext = () => {
  const context = useContext(AppContext);
  if (!context) throw new Error('useAppContext must be used within AppProvider');
  return context;
};

// Parent Component
import { useAppContext } from './context';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const { message } = useAppContext();
  
  return (
    <div>
      <h1>Parent Component</h1>
      <p>Received from Context: {message}</p>
      <ChildComponent />
    </div>
  );
};

export default ParentComponent;

// Child Component
import { useAppContext } from './context';

const ChildComponent = () => {
  const { setMessage } = useAppContext();
  
  return (
    <div>
      <button onClick={() => setMessage('Hello from Child!')}>
        Update Message
      </button>
    </div>
  );
};

export default ChildComponent;

With React Context:

  • AppContext provides shared state (message) and a function (setMessage) to update it.
  • The AppProvider wraps the components that need access to this context, making it available to both the ParentComponent and ChildComponent.

Best Practices for Passing Values Between Components

When passing values between parent and child components, following best practices helps ensure code maintainability, readability, and scalability.

  1. Prop-Drilling: Avoid Excessive Nesting
    • While passing props is straightforward, excessive prop-drilling (passing data through many levels of nested components) can lead to messy code. In these cases, consider using React Context or state management libraries like Redux to avoid passing props down through every level.
  2. Keep Components Reusable
    • Child components should remain reusable. If a child component needs data from the parent, pass it as props. Avoid making child components too dependent on their parents, as this reduces reusability.
  3. Use Descriptive Prop Names
    • Use descriptive names for props to make it clear what data is being passed. Avoid generic names like data or item. Instead, name props according to their content, like message, userDetails, or post.
  4. Lifting State Up
    • When passing data from child to parent, always lift the state up to the nearest common ancestor. This ensures the parent component can handle and update the state while keeping the child components as dumb (stateless) as possible.
  5. Type Checking with TypeScript
    • When working with TypeScript, always define types for your props. This adds clarity to the expected data and helps prevent runtime errors. Use interfaces to define the shape of props passed to components.
  6. Avoid Passing Functions Inline
    • Avoid defining functions inline in JSX (e.g., <ChildComponent onChange={handleChange()}>). This can lead to unnecessary re-renders. Instead, define the function outside the render method or as part of the component’s logic.
  7. Using Default Props (Optional)
    • To provide fallback values for props that might not be passed, consider using defaultProps. This ensures components behave consistently even when certain props are missing.
    ChildComponent.defaultProps = { message: 'Default message' };

Conclusion

Passing values between parent and child components is a fundamental part of building React and Next.js applications. By using props, callback functions, and context, you can easily manage data flow between components. Following best practices such as keeping components reusable, managing state properly, and using TypeScript for type safety will help make your application more maintainable and scalable in the long run.

Happy Coding!

Building an Open Graph Image Fetcher with Angular

I’m always interested in understanding how SEO works. This time, I wanted to learn how the Open Graph (OG) image is fetched from a source when we paste a URL into tools like Slack or social media platforms like Facebook or Twitter. By default, these platforms bring some image as a thumbnail or preview. I learned that this image is called an OG image.
In this blog, we built a small solution to simulate fetching an OG image. We also explored an alternative way to fetch the image using a different approach. Let’s dive into the details!

Building an Open Graph Image Fetcher with Angular

In this blog post, we’ll walk through building a simple Open Graph Image Fetcher using Angular. This application will allow users to enter a URL, fetch the Open Graph image associated with that URL, and display it.

Step 1: Setting Up the Angular Project

First, create a new Angular project if you haven’t already:

ng new open-graph-image-fetcher
cd open-graph-image-fetcher

Step 2: Install Dependencies

We’ll need the HttpClientModule for making HTTP requests. So add it accordingly

Step 3: Create the Service

Create a service to handle fetching the Open Graph image. We’ll use the opengraph.io API for this purpose. Note that you need to get an API key from opengraph.io and add it to your environment configuration.

open-graph.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class OpenGraphService {
  private apiKey = environment.openGraphApiKey; // Use API key from environment

  constructor(private http: HttpClient) {}

  fetchOGImage(url: string): Observable<string> {
    const apiUrl = `https://opengraph.io/api/1.1/site/${encodeURIComponent(url)}?app_id=${this.apiKey}`;
    return this.http.get(apiUrl).pipe(
      map((response: any) => {
        console.log('response', response);
        const ogImage = response.hybridGraph.image;
        return ogImage || '';
      })
    );
  }
}

Step 4: Create the Component

Create a component to handle user input and display the fetched Open Graph image.

app.component.ts

import { Component } from '@angular/core';
import { OpenGraphService } from './open-graph.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  ogImage: string | undefined;
  targetURL = 'https://www.example.com';
  loading = false;

  constructor(private openGraphService: OpenGraphService) {}

  fetchOGImage() {
    this.loading = true;
    this.openGraphService.fetchOGImage(this.targetURL).subscribe(
      (image: string) => {
        this.ogImage = image;
        this.loading = false;
      },
      (error) => {
        console.error('Error fetching Open Graph image', error);
        this.loading = false;
      }
    );
  }
}

app.component.html

<div class="container">
  <h1>Open Graph Image Fetcher</h1>
  <div class="content">
    <input type="text" placeholder="Enter URL" [(ngModel)]="targetURL" (keyup.enter)="fetchOGImage()" class="url-input" />
    <button (click)="fetchOGImage()">Fetch Open Graph Image</button>
    <div *ngIf="loading" class="loader"></div>
    <div *ngIf="ogImage && !loading" class="image-container">
      <img [src]="ogImage" alt="Open Graph Image">
    </div>
  </div>
</div>

app.component.scss

.container {
  text-align: center;
  margin-top: 50px;
}

.content {
  display: inline-block;
  text-align: left;
}

.url-input {
  margin-right: 10px; /* Add space between the textbox and the button */
}

.loader {
  border: 16px solid #f3f3f3; /* Light grey */
  border-top: 16px solid #3498db; /* Blue */
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite;
  margin: 20px auto;
}

.image-container {
  height: 300px; /* Fixed height to prevent jumping */
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-container img {
  max-height: 100%;
  max-width: 100%;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

Alternative Approach: Using Cheerio

Another way to fetch Open Graph data is by using Cheerio, a server-side library that parses HTML and extracts data. However, this approach has limitations, such as proxy issues and the requirement of server-side blocks.

Conclusion

In this blog post, we built a simple Open Graph Image Fetcher using Angular and the opengraph.io API. We also explored an alternative approach using Cheerio on a Node.js server. While the Cheerio approach can be useful, it has limitations such as proxy issues and the requirement of server-side blocks.

Find the source here at GitHub

https://github.com/PandiyanCool/open-graph-image

Feel free to expand on this project by adding more features or improving the UI.

Happy coding!