How to Build Synchronized Input Component in React

Sync data

Introduction

In modern web applications, users often expect real-time synchronization across multiple tabs or devices. In this tutorial, we’ll dive into creating a Synchronized Input component using React, which enables users to type in one tab and see the changes reflected in other open tabs simultaneously. Let’s explore how to implement this functionality step by step.

Explanation

1. Setting Up the Component

import React, { useState, useEffect, useRef } from "react";
import "./BroadCast.css"; // Import your CSS file

const SyncedInput = () => {
  const [text, setText] = useState("");
  const [syncEnabled, setSyncEnabled] = useState(false);
  const broadcastChannelRef = useRef(null);

  useEffect(() => {
    // Initialize the Broadcast Channel
    broadcastChannelRef.current = new BroadcastChannel("textChannel");
    // Listen for messages from other tabs
    broadcastChannelRef.current.onmessage = (event) => {
      setText(event.data);
    };
    // Cleanup function
    return () => {
      broadcastChannelRef.current.close();
    };
  }, []);

  // Handle input change
  const handleChange = (e) => {
    const newText = e.target.value;
    setText(newText);
    if (syncEnabled) {
      // Broadcast the updated text to other tabs
      broadcastChannelRef.current.postMessage(newText);
    }
  };

  // Handle toggle sync checkbox
  const handleToggleSync = () => {
    setSyncEnabled(!syncEnabled);
    if (!syncEnabled) {
      // Broadcast the current text to other tabs when sync is enabled
      broadcastChannelRef.current.postMessage(text);
    }
  };

  return (
    <div className="synced-input-container">
      <input
        type="text"
        value={text}
        onChange={handleChange}
        placeholder="Type here..."
        className="synced-input-field"
      />
      <label className="synced-checkbox">
        <input
          type="checkbox"
          checked={syncEnabled}
          onChange={handleToggleSync}
        />
        Sync across tabs
      </label>
    </div>
  );
};

export default SyncedInput;
JSX

Explanation:

  • State Management: Utilize React’s useState hook to manage the text input value and synchronization toggle state.
  • Broadcast Channel: Use the BroadcastChannel API to establish communication between tabs.
  • Effect Hook: Set up the Broadcast Channel and define event listeners to handle incoming messages and cleanup when the component unmounts.
  • Input Change Handler: Implement a function to update the input value and broadcast changes to other tabs when synchronization is enabled.
  • Toggle Sync Handler: Toggle synchronization on/off and broadcast the current text to other tabs when enabled.

2. Styling the Component

.synced-input-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}

.synced-input-field {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
  font-size: 16px;
}

.synced-checkbox {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.synced-checkbox input {
  margin-right: 5px;
}
CSS

Explanation:

  • Container Styling: Center the input and checkbox horizontally and vertically.
  • Input Field Styling: Apply padding, border, and border-radius to the input field.
  • Checkbox Styling: Adjust the font size and alignment of the checkbox label.

Conclusion

By following this tutorial, you’ve learned how to create a Synchronized Input component in React, allowing users to seamlessly share input data across multiple tabs. This feature enhances collaboration and user experience in web applications. Feel free to customize the component’s appearance and behavior to suit your project requirements.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *