0

I'm making a first basic MERN Stack where users can enter their name, age and give one link for their social media as like a log book that they visited the page. After taking the link from the user in schema as follows

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,

    },
    age: {
        type: Number,
        required: true,
    },
    socialname: {
        type: String,
        required: true,
    },
    social: {
        type: String,
        required: true,
    },

});

Now I'm trying to display the link in react with this code

     <div>
              <h1>{user.name} was here!</h1>
              <h1>Age: {user.age}</h1>
              <p>Find me on <a href={user.social} target="_blank">{user.socialname}</a></p>
            </div>
          );
        })}
      </div>

Now the issue is rather than opening a link I give in the DB (for ex: twitter.com/updwnheadlights) it is opening the link as (http://localhost:3000/twitter.com/updwnheadlights) how can I solve something like this?

I was trying to make sure that when you click on the social media name, the link given by the user open

  • `https://twitter.com/updwnheadlights`? – Konrad Jan 23 '23 at 18:32
  • You need to add the protocol to the beginning of the URL (http:// or https://) if it's not already there, otherwise the URL is treated as a local path. – Henry Woody Jan 23 '23 at 18:32
  • It's unrelated to react, mongo or mern. It's just how html works – Konrad Jan 23 '23 at 18:34
  • Okay thanks adding https:// seamed to have worked, but what if someone who enters their information does not put the link with "https://" ? sorry if this is a dumb question, I'm new to all this – Ayush Desai Jan 23 '23 at 18:35
  • Just check if the URL includes the protocol before adding it, for example: `(hasProtocol(user.social) ? "" : "https://") + user.socal`, where `hasProtocol` can be implemented like this: `/^https?:\/\//.test(url)` – Henry Woody Jan 23 '23 at 18:38

0 Answers0