React URL Parser - JavaScript Exercise #25

React URL Parser - JavaScript Exercise #25

Build a React URL parser component

ยท

5 min read

Overview

In this exercise, you will be creating a React URL parser that will take in a URL string and extract specific information from it. This can be useful in many different scenarios, such as when building a search engine or analyzing website traffic.

Instructions

  1. Create a new React component called UrlParser.

  2. Add a state variable to hold the URL string that will be parsed.

  3. Create a form element that allows users to input a URL string.

  4. Add an event listener to the form that updates the state variable when the form is submitted.

  5. Write a function that parses the URL string and extracts the following information:

    • Protocol (e.g. http, https)

    • Domain name (e.g. google.com)

    • Port number (if present)

    • Path (e.g. /search)

    • Query parameters (if present)

  6. Display the parsed information in the component.

  7. Test your component with different URLs to ensure that it correctly extracts the relevant information.

Bonus Requirements

  1. Add error handling to your component to handle invalid URL strings.

  2. Allow users to edit the parsed information and update the URL string accordingly.

  3. Create a "copy URL" button that copies the parsed URL to the clipboard.

  4. Add additional functionality to extract and display other information, such as the fragment identifier (e.g. #section) or user credentials (e.g. username:password@).

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React URL parser exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the URL Parser exercise

import React, { useState } from "react";

const UrlParser = () => {
  const [url, setUrl] = useState("");
  const [parsedUrl, setParsedUrl] = useState({});

  const handleFormSubmit = (event) => {
    event.preventDefault();
    try {
      const urlObj = new URL(url);
      const parsed = {
        protocol: urlObj.protocol,
        domain: urlObj.hostname,
        port: urlObj.port,
        path: urlObj.pathname,
        queryParams: Object.fromEntries(urlObj.searchParams.entries()),
        fragmentId: urlObj.hash
      };
      setParsedUrl(parsed);
    } catch (error) {
      alert("Invalid URL. Please try again.");
    }
  };

  const handleParsedUrlChange = (event) => {
    const { name, value } = event.target;
    setParsedUrl((prevState) => ({ ...prevState, [name]: value }));
  };

  const handleCopyUrl = () => {
    navigator.clipboard.writeText(url);
  };

  return (
    <div>
      <form onSubmit={handleFormSubmit}>
        <label htmlFor="url-input">Enter a URL:</label>
        <input
          type="text"
          id="url-input"
          name="url"
          value={url}
          onChange={(event) => setUrl(event.target.value)}
        />
        <button type="submit">Parse</button>
      </form>
      <br />
      <div>
        <h2>Parsed URL:</h2>
        <p>Protocol: {parsedUrl.protocol}</p>
        <p>Domain: {parsedUrl.domain}</p>
        <p>Port: {parsedUrl.port}</p>
        <p>Path: {parsedUrl.path}</p>
        <p>Query Params: {JSON.stringify(parsedUrl.queryParams)}</p>
        <p>Fragment Identifier: {parsedUrl.fragmentId}</p>
      </div>
      <br />
      <div>
        <h2>Edit Parsed URL:</h2>
        <label htmlFor="protocol-input">Protocol:</label>
        <input
          type="text"
          id="protocol-input"
          name="protocol"
          value={parsedUrl.protocol}
          onChange={handleParsedUrlChange}
        />
        <br />
        <label htmlFor="domain-input">Domain:</label>
        <input
          type="text"
          id="domain-input"
          name="domain"
          value={parsedUrl.domain}
          onChange={handleParsedUrlChange}
        />
        <br />
        <label htmlFor="port-input">Port:</label>
        <input
          type="text"
          id="port-input"
          name="port"
          value={parsedUrl.port}
          onChange={handleParsedUrlChange}
        />
        <br />
        <label htmlFor="path-input">Path:</label>
        <input
          type="text"
          id="path-input"
          name="path"
          value={parsedUrl.path}
          onChange={handleParsedUrlChange}
        />
        <br />
        <label htmlFor="query-params-input">Query Params:</label>
        <input
          type="text"
          id="query-params-input"
          name="queryParams"
          value={JSON.stringify(parsedUrl.queryParams)}
          onChange={handleParsedUrlChange}
        />
        <br />
        <label htmlFor="fragment-id-input">Fragment Identifier:</label>
        <input
          type="text"
          id="fragment-id-input"
          name="fragmentId"
          value={parsedUrl.fragmentId}
          onChange={handleParsedUrlChange}
        />
        <br />
        <button onClick={handleCopyUrl}>Copy URL</button>
      </div>
    </div>
  );
};

export default UrlParser;
import React from 'react';
import UrlParser from './UrlParser';

function App() {
  return (
    <div className="App">
      <UrlParser />
    </div>
  );
}

export default App;

Example applications where the UrlParser component can be used:

  1. Search engine - When building a search engine, you can use the UrlParser component to extract information from the URLs of the search results. This can help you analyze the search results and improve the search algorithm.

  2. Analytics dashboard - In an analytics dashboard, you can use the UrlParser component to extract information from the URLs of the website traffic. This can help you track the performance of the website and identify the areas that need improvement.

  3. Bookmark manager - In a bookmark manager application, you can use the UrlParser component to extract information from the URLs of the bookmarked websites. This can help you organize the bookmarks and make them more accessible.

  4. Social media platform - When building a social media platform, you can use the UrlParser component to extract information from the URLs of the shared posts. This can help you analyze the engagement of the posts and improve the content strategy.

  5. E-commerce website - On an e-commerce website, you can use the UrlParser component to extract information from the URLs of the product pages. This can help you track the performance of the products and identify the popular products.

UrlParser component is a versatile tool that can be used in various applications to extract information from URLs. With the ability to parse the protocol, domain, port, path, query parameters, and fragment identifier of a URL, this component can be used in many different contexts to improve the functionality and user experience of a web application. Its flexible nature makes it a valuable addition to any developer's toolbox.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย