I have written my code where I must Fetch data from API on button, but for more easier and cleaner page I want to have toggle button, but i dont know how to implement it in my function and into my render method.
I tried with state, and function, but dont know how to write it in render.
import React from "react";
import "./FetchBeerStyle.css";
export default class FetchBeer extends React.Component {
constructor(props) {
super(props);
this.state = {
beers: [],
on:false,
}
}
handleClick = () => {
fetch('https://api.punkapi.com/v2/beers')
.then(res => {
if (!res.ok) {
throw new Error('There has been an error');
}
return res.json();
})
.then(data => {this.setState({ beers: data})
console.log(this.state.beers);
})
.catch(e => console.log(e))
}
render(){
return (
<div>
<button onClick={this.handleClick}>Get All Beers/Return</button>
{this.state.beers.map((beer) => {
return <div key={beer.id}>
<h1 className="h1" >NAME : {beer.name}</h1>
<img src= {beer.image_url}/>
<h2>TAGLINE : {beer.tagline}</h2>
<p>FIRST BREWED : {beer.first_brewed}</p>
<p> DESCRIPTION : <br></br>{beer.description}</p>
<p> FOOD PAIRING : <br></br>{beer.food_pairing}</p>
<p> ALCOHOL BY VOLUME(%) : {beer.abv}</p>
<p> pH : {beer.ph}</p>
</div>
})}
</div>
);
}
}
You can check if button is true or false then you render your data. Also you need to call a different function that changes you button's state on click and call you function "handleClick" to fetch the data.
`{
this.state.on ?
this.state.beers.map((beer) => {
return <div key={beer.id}>
<h1 className="h1" >NAME : {beer.name}</h1>
<img src= {beer.image_url}/>
<h2>TAGLINE : {beer.tagline}</h2>
<p>FIRST BREWED : {beer.first_brewed}</p>
<p> DESCRIPTION : <br></br>{beer.description}</p>
<p> FOOD PAIRING : <br></br>{beer.food_pairing}</p>
<p> ALCOHOL BY VOLUME(%) : {beer.abv}</p>
<p> pH : {beer.ph}</p>
</div>
})
: null }`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.