EN
React - button with AJAX request
2
points
Below example shows buton that sends some GET request on mouse click action.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";
const App = () => {
const [response, setResponse] = React.useState();
const handleClick = async () => {
const text = "Some text here...";
try {
const response = await fetch(`/examples/echo?text=${encodeURIComponent(text)}`);
const responseText = await response.text();
setResponse(`Response: ${responseText}`);
} catch (error) {
setResponse("Request error!");
}
};
return (
<div>
<button onClick={handleClick}>Send request!</button>
{response && <div>{response}</div>}
</div>
);
};
const root = document.querySelector("#root");
ReactDOM.render(<App />, root);