EN
React - button with AJAX request
2 points
Below example shows buton that sends some GET request on mouse click action.
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from "react";
3
// import ReactDOM from "react-dom";
4
5
const App = () => {
6
const [response, setResponse] = React.useState();
7
const handleClick = async () => {
8
const text = "Some text here...";
9
try {
10
const response = await fetch(`/examples/echo?text=${encodeURIComponent(text)}`);
11
const responseText = await response.text();
12
setResponse(`Response: ${responseText}`);
13
} catch (error) {
14
setResponse("Request error!");
15
}
16
};
17
return (
18
<div>
19
<button onClick={handleClick}>Send request!</button>
20
{response && <div>{response}</div>}
21
</div>
22
);
23
};
24
25
const root = document.querySelector("#root");
26
ReactDOM.render(<App />, root);