How to pass variable in URL React js



in react js I made a simple date picker and select date from the dropdown calendar and I displayed it in the console.

that date stored in a variable, now how to use that variable in URL

My questions :

  1. How to pass parameter in React js URL

  2. how to print parameter in console log

code:

import React, { Component } from 'react'
import axios from 'axios'
class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            key: '',
            
        }
    }

    changeHandler = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    submitHandler = e => {
        e.preventDefault()
        console.log(this.state)
        axios
            .get('http://127.0.0.1:8000/hvals_hash?key=31/8/21')
            .then(response => {
                console.log(response)
            })
            .catch(error => {
                console.log(error)
            })
    }

    render() {
        const { key } = this.state
        return (
            <div>
                <form onSubmit={this.submitHandler}>
                    <div>
                        <input
                            type="text"
                            name="key"
                            value={key}
                            onChange={this.changeHandler}
                        />
                    </div>

                    <button type="submit">Submit</button>
                </form>
            </div>
        )
    }
}

export default PostForm

A date is from date picker form , so pass date dynamicall how to do that

Answer

You can use template literals to pass dynamic values as follows.

componentDidMount(){
    const date = "20/8/21";
    axios.get(`http://127.0.0.1:8000/hvals_hash?key=${date}`)
    .then(response => {
        this.setState({
            posts:response.data
        })
        console.log(response.data)


    })
}


Source: stackoverflow