Home > Software design >  Returning the base URL in React
Returning the base URL in React

Time:11-01

I'm trying to use the base URL in an object:

      {
        id: "1",
        url: {baseURL}   "/img1.jpg",
        fileName: "img1.jpg",
      }

Here is how I'm trying to do it:

const currentRoute= window.location.pathname

But this is returning [object Object]/images/img1.jpg.

CodePudding user response:

if baseURL is a string, then {baseURL} would convert it to an object. And due to the openness of javascript, it would try to call the toString() method on the object which would result in [object Object].

You should try using string templates like `${baseURL}/img1.jpg` or just do baseURL "/img1.jpg". And if the baseURL is inside the currentRoute then do currentRoute.baseURL "/img1.jpg" or destructure it before concatenation like - const { baseURL } = currentRoute; then do url: baseURL "/img1.jpg". Check this link for more info on object destructuring.

CodePudding user response:

      {
        id: "1",
        url: baseURL   "/img1.jpg", // => remove brackets
        fileName: "img1.jpg",
      }

CodePudding user response:

If you want to use brackets, you need to use Template Literals.

Else you can just do what the others in this Post has said, just remove the barcketes.

let object = {
    id: "1",
    url: `${baseUrl}/img1.jpg`, // Example of a template literal.
    fileName: "img1.jpg",
  }
  • Related