Home > Blockchain >  How to get the number of url in React?
How to get the number of url in React?

Time:12-08

I want to get the number in the path url. Example of url https://stackoverflow.com/questions/7/ask. I want to get the number 7 and put it to the state.

CodePudding user response:

You could use useParams hook from "react-router-dom". Here's the link for more details.

CodePudding user response:

In order to get the number in the path of a URL, you should use the useParams hook in the react-router-dom package. This hook will allow you to access the dynamic portions of the URL path as parameters.

Here is an example:

import { useParams } from "react-router-dom";

function MyComponent() {
    
    //  getting the URL parameters
    const { number } = useParams();

    //  setting the number in the URL path as the initial state
    const [state, setState] = useState(number);

    //  using the state value as needed within the component
    return (
        <div>
            The number in the URL path is: {state}
        </div>
    );
}

CodePudding user response:

import React, { useState } from 'react';

function App() {
  const [number, setNumber] = useState(null);

  const handleUrlChange = (event) => {
    // extract the number from the URL
    const url = event.target.value;
    const numberMatches = url.match(/\d /);
    const extractedNumber = numberMatches ? numberMatches[0] : null;

    // set the number as a state variable
    setNumber(extractedNumber);
  }

  return (
    <div>
      <h1>Extract Number from URL</h1>
      <input type="text" onChange={handleUrlChange} placeholder="Enter a URL" />
      {number && <p>The number in the URL is: {number}</p>}
    </div>
  );
}

We start with a state variable 'number' thats initial value is set to null. When the user enters a URL in the input field, the 'handleUrlChange' event handler is called. It then extracts the number using a regular expression and sets that value as the new state value.

  • Related