Home > database >  How can I do to make clickable an url in a string?
How can I do to make clickable an url in a string?

Time:12-28

Hello I have that code :

import "./styles.css";
import React, { useState } from 'react';

const App = () => {
  const [myString, setMyString] = useState("Hello I use https://www.google.com/")
  return (
    <div className="App">
      <h1>{myString}</h1>
    </div>
  );
}

export default App;

This link https://www.google.com/ is not clickable, you can see that here :

The full project

How can I do to make it clickable ?

CodePudding user response:

You have to wrap your link in an anchor tag and set the href attribute to its relative address.

import "./styles.css";

export default function App() {
  const link = "https://www.google.com";
  const myString = "Hello I use ";
  return (
    <div className="App">
      <h1>Hello CodeSandbox </h1>
      <h2>
        {myString}
        <a href={link}>{link}</a>.
      </h2>
    </div>
  );
}

CodePudding user response:

Although I am not confessed why you have to use State for this. But you can achieve your desired result by doing the following.

import "./styles.css";
import React, { useState } from 'react';

const App = () => {
  const [myString, setMyString] = useState("Hello I use https://www.google.com/"); 
  
  let result = myString.split(' ');
  const URL  = result[3];
 
  return (
    <div className="App">
      <h1> <a href={URL}> {URL}</a></h1>
    </div>
  );
}

export default App;
  • Related