Home > Mobile >  How to use dynamic url in nextjs
How to use dynamic url in nextjs

Time:07-14

I am working with nextjs,I am fetching image(via api),Right now i am getting "Full image path"(for example,"https//myurl.com/image/imagename.jpg") so i am fetching without any problem,but i want to know that if i have only "image name"(for example,"imagename.jpg") so how can we fetch in front end ? in other words how can i pass "url/hostname" before imagename ? Should i create seprate "component" and mention "host url" and fetch whereever i want OR Should i create "variable" like following code or is there another way ?

class Company extends React.Component {
    const orig = 'http://anyurl.com';

    state = {
        trending: []
      }
    componentDidMount() {
        axios.get('https://myurl.com/apipath',
        )
          .then(res => {
            const trending = res.data;
            this.setState({ trending });
          })
      }

    render() {
            return 
                (

                    <img src={post.image} /> 
                );      
            );
        }

CodePudding user response:

If you know the base URL, you can use Template Literals for the same. For Example:

const orig = 'https://myurl.com/apipath';
const imageName = 'image1.jpg';
const imgUrl = `${orig}/${imageName}`

CodePudding user response:

Make a separate Variable and add them like this ${} in string literal. then you will use dynamic fetching.

CodePudding user response:

You can create a variable baseURL that contains a constant path to your backend URL. This would be static. The only dynamic part is your imageFileName. You can store this in state or get it from props or where ever you are getting the imagename.jpg from.

When you want to define some constant values like style or image URLs then it's always better to define that outside of component. It will become global values and available inside each function/class of that file.

config/urlConfig.js

export const urlConfig={
    baseURL: 'http://myurl.com/image/'
}

//Your component

import { urlConfig } from 'path/to/your/config/urlConfig';
class Company extends React.Component {
    state = {
        trending: [],
        imageFileName: 'imagename.jpg'   // Assign any value to this
      }
    componentDidMount() {
        axios.get(urlConfig.baseURL   this.state.imageFileName,
        )
          .then(res => {
            const trending = res.data;
            this.setState({ trending });
          })
      }

    render() {
            return 
                (

                    <img src={post.image} /> 
                );      
            );
        }
  • Related