So I'm trying to render some JSX when a user presses a button, I'm trying to do this via onClick but it is not working, The JSX does not get rendered on the screen. Is there a way to do this? My code is like this:
function RandomScreen() {
async function HandleClick() {
// make API post request
.then(function(response) {
return (<h1>{response.data}</h1>)
})
}
return (
<button onClick={HandleClick}>Click me</button>
)
}
I think you are looking for something like this:
function RandomScreen() {
const [data, setData] = useState(null);
async function HandleClick() {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
}
return (
<button onClick={HandleClick}>
Click me
{data && <h1>{JSON.stringify(data, null, 2)}</h1>}
</button>
);
}
store your data in a state for example
const [data, setData] = React.useState();
...
.then(function(response) {
setData(response.data);
})
and in JSX you can handle the display part:
{data && <h1>{data}</h1>}
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.