React
01. Getting Started
## ------------------| Create
npm init react-app myapp
cd myapp
npm start
## ------------------| Deploy to production
npm run build
02. React Hooks
import React, { useState } from 'react';
function App() {
const [value, setValue] = useState("This is initial value");
return (
<div>
<button onClick={() => setValue("Value changed")}>Default</button>
<h1>{value}</h1>
</div>
);
}
export default App;
03. Back-End Integration
Fetching data from backend when page loads
import React, { useEffect, useState } from 'react';
function App() {
const [results, setResults] = useState("");
useEffect(() => {
const fetchResults = async () => {
const response = await fetch("https://h4rithd.com/test");
const responseObj = await response.text();
setResults(responseObj);
// For JSON objects
// const responseObj = await response.json();
// setResults(responseObj.value);
};
fetchResults();
}, []);
return (
<p>{results}</p>
);
}
export default App;
Submitting data to backend
import React, { useState } from 'react';
function App() {
const [form, setForm] = useState({
item: "",
});
const createItemSubmit = (e) => {
e.preventDefault(); // Prevent refeshing the page
fetch("https://h4rithd.com/test", {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json' // or 'application/x-www-form-urlencoded'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(form)
});
};
return (
<div>
<form>
<input onChange={(e) =>
setForm({
...form,
item: e.target.value
})}
name="item"></input>
<button type="submit" onClick={createItemSubmit}>Submit</button>
</form>
</div>
);
}
export default App;
Last updated