I am trying to make a page consuming an API with react, but the question arose: What is the correct way to show the value of a variable in react?
I know you can do something like:
<h2>{variable}</h2>
But being inside a function, it doesn't let me do that, I have it like this:
const callback = (res) => {
const htmlCity = document.getElementById('city-name')
let cityName = res.data.name //Esta es la variable que quiero mostrar
htmlCity.innerHTML = `City: ${cityName}`
}
And the html like so:
<h2 id="city-name">City: </h2>
Thank you very much for your reply
React
it works based on states that can be modified for any reason. Those states must be checked for React to be able to work with them.So if you need to create a variable, and said variable is going to change throughout the flow - either because it depends on the value of an input, a select or some DOM element -, you need to create a state that controls the change of that variable.
For your case it would be
Where through the useState hooks , we control the state of our element, and in the function
handleChange
, we assign the value entered in the input to said state throughsetCity
. Finally you just show the variable as you already know how to do it.If you have any questions, tell us
the best thing you can do is use useState which is a Hook for the state in this case of the constant and you can give it an initial value as in the example or blank and send the data in this case with an input a
setCityName
, so the code, hope it helps.