Connect Highlight Functionality in React with Backend: A Complete Guide (2026)

Discover how to connect text highlighting in React to a backend using SlateJS and Node.js, ensuring your highlights persist across sessions.

Connect Highlight Functionality in React with Backend: A Complete Guide (2026)

Connect Highlight Functionality in React with Backend: A Complete Guide (2026)

In this tutorial, you'll learn how to connect a text highlighting feature in a React application to a backend or local storage solution. This is essential for applications where users need to save their progress, such as educational tools or collaborative editors. We'll use React, SlateJS, and a simple Node.js backend to demonstrate this process.

Key Takeaways

  • Learn how to implement text highlighting in React using SlateJS.
  • Understand how to send highlighted text data to a backend server.
  • Explore how to manage state and handle asynchronous operations in React.
  • Gain insights into connecting React frontend with a Node.js backend.

Text highlighting and commenting are crucial for many applications that deal with textual data. While highlighting may seem straightforward, ensuring that these highlights persist across sessions involves backend integration. This guide will walk you through setting up a basic system to achieve this, focusing on the highlight feature.

Prerequisites

  • Basic knowledge of React and JavaScript (ES6+).
  • Familiarity with Node.js and Express for the backend.
  • Understanding of SlateJS for rich text editing.
  • Node.js and npm installed on your machine.
  • A REST client like Postman for testing backend endpoints.

Step 1: Set Up the React Project

First, we'll set up a new React application using Create React App. SlateJS will be used for the text editor component.

npx create-react-app highlight-app
cd highlight-app
npm install slate slate-react

After setting up the project, ensure your application runs correctly by executing npm start.

Step 2: Implement SlateJS for Text Editing

SlateJS provides a customizable framework for building rich text editors. Let's configure a basic editor that allows text selection and highlighting.

import React, { useCallback, useMemo } from 'react';
import { Slate, Editable, withReact } from 'slate-react';
import { createEditor } from 'slate';

const TextEditor = () => {
  const editor = useMemo(() => withReact(createEditor()), []);
  const initialValue = useMemo(() => [{ type: 'paragraph', children: [{ text: 'Select and highlight text here.' }] }], []);

  return (
     console.log(value)}>
       }
        onKeyDown={event => {/* Handle key events for styling */}}
      />
    
  );
};

const Leaf = ({ attributes, children, leaf }) => {
  return {children};
};

export default TextEditor;

This code sets up a basic text editor where we can later add highlighting functionality.

Step 3: Enable Text Highlighting

Next, we need to implement the functionality to highlight text. We'll modify the editor to toggle a highlight on selected text.

const toggleHighlight = (editor) => {
  // Check if currently highlighted
  const isActive = isHighlightActive(editor);
  // Set highlight
  editor.addMark('highlight', !isActive);
};

const isHighlightActive = (editor) => {
  const [match] = Editor.nodes(editor, {
    match: n => n.highlight === true,
    universal: true,
  });
  return !!match;
};

Integrate toggleHighlight into the editor's onKeyDown method to toggle highlighting.

Step 4: Set Up a Node.js Backend

To persist highlights, we'll create a simple backend using Express. This backend will receive highlight data from the frontend.

mkdir highlight-backend
cd highlight-backend
npm init -y
npm install express body-parser cors

Here's a basic server setup:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());

let highlights = [];

app.post('/highlights', (req, res) => {
  highlights = req.body;
  res.status(200).send('Highlights saved successfully');
});

app.get('/highlights', (req, res) => {
  res.status(200).json(highlights);
});

app.listen(4000, () => console.log('Server running on port 4000'));

Step 5: Connect React Frontend with Backend

Now, let's connect the React frontend to this backend service and send highlighted text to be saved.

const saveHighlights = async (highlights) => {
  try {
    const response = await fetch('http://localhost:4000/highlights', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(highlights),
    });
    if (response.ok) {
      console.log('Highlights saved.');
    } else {
      console.error('Failed to save highlights.');
    }
  } catch (error) {
    console.error('Error:', error);
  }
};

Call saveHighlights whenever a highlight change occurs in the editor.

Common Errors/Troubleshooting

  • Server Not Responding: Ensure that the backend server is running on the correct port.
  • CORS Issues: Double-check that CORS is enabled on the backend server.
  • Highlight Not Toggling: Verify the logic in the toggleHighlight function and ensure proper selection handling.

By following these steps, you can create a robust text highlighting feature in React that persists user data across sessions, enhancing the user experience significantly.

Frequently Asked Questions

How do I install SlateJS?

You can install SlateJS using npm with the command npm install slate slate-react.

Why use Node.js for the backend?

Node.js offers a lightweight, efficient platform for building RESTful APIs, making it ideal for handling requests from React apps.

What if CORS errors occur?

Ensure that your backend server has CORS enabled to allow requests from your frontend domain.