Nice! So it’s on to the front-end.
I’m not familiar with that course, but it looks similar to the Node + ExpressJS back-end & React front-end model used in the FCC courses.
This is my method for using create-react-app with a back-end; there are other, particularly more server “hot-reload” equipped strategies out there.
Start with a proxy attribute in the react app’s package.json. The creator’s can explain it better than I can. You’d want to proxy to port 3000 since that’s what the express server they made is using. It may not even be truly necessary as I think CRA’s default port is 3000 anyhow, but it’s good practice I guess. I find it easy to just feed the server start script another port to use (PORT=4000
) during development, and keep the React app at it’s default but it’s whatever works for you.
You’ll need to tell the express app where the assets and index page are located in relation to itself. This goes back to that index.js modification I noted above. For React apps the static folder to point to is the build folder. The Path
module and the __dirname
variable are useful here for constructing directory paths.
The server needs to be started after building the React app.
A basic workflow for me would be to open a shell and navigate to the create-react-app then npm start
. I’d make any changes to the front-end I needed then terminate the CRA dev server. Then npm run build
. Next, navigate to the the server folder and start it up, in this case it happens to be the same as the React app, npm start
. Finally it’s to the browser at port 3000 again to check out how it runs using the server.
As for “how to connect everything,” you have a lot of options. They’ve already wired up the server for you, so you’re really just telling the React app to fetch the data from certain API end-points and then display it somewhere within the app. The easiest options, IMO, are fetch
or XMLHttpRequest
.
Something like:
// Somewhere inside the main React App Class
componentDidMount() {
// arbitrarily load the search API results on mount
// this could also go in a button onClick or whatever else
const xhr = new XMLHttpRequest(); // Why not pick the most verbose option
const searchLength = 12,
searchSort = 'DISTANCE';
xhr.open(`/api/search?${searchLength}&sorting=${searchSort}`) // The search API URL
// Callback to execute when response is recieved from server
xhr.onload = async () => {
const data = await JSON.parse(xhr.response.data);
// You probably want to validate and clean any response data first, in reality
this.setState({ resultsToDisplay: data }); // Store JSON data in app state
}
}
xhr.send();
}
Maybe have the “/api/profile” endpoint called in a similar way on a mouse event (click or hover) for each result?