I currently have express set up to serve a static html page where my react components mount to. I'm also using react router because I have nested routes. For example:
I have an App component (green outline). Within that component, I'm rendering a Header component (orange outline) and a Footer component (red outline) and passing in a Review component (blue outline) through this.props.children.
My server.js file (express):
const express = require('express');
const app = express();
app.use(express.static('dist'));
const PORT = process.env.PORT || 3000;
app.listen(PORT, function() {
console.log(`Listening on port ${PORT}...`);
});
My routes.js file (react-router):
import React from 'react';
import ReactRouter, {
Router,
Route,
browserHistory,
IndexRoute,
} from 'react-router';
import App from '../components/App';
import Home from '../components/Home';
import Review from '../components/Review';
import Game from '../components/Game';
const routes = (
<Router history={browserHistory}>
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="/game/:id" component={Game} />
<Route path="/game/:id/review" component={Review} />
<Route path="*" component={Home} />
</Route>
</Router>
);
export default routes;
My question is, I want to be able to make GET/POST requests (GET from the Game component to display all reviews from a db and POST to create a new review from the Review component), but where should that happen? I can't tell if it has to happen in my express routes because it seems to me that all express is doing is rendering the static html page and then react-router is taking over after that with handling which components to display.
Any and all help is greatly appreciated.
For the GET
request, you can load initial data in a separate function, than load that data in after the component has mounted using componentDidMount
like so:
class Game extends React.Component {
constructor() {
this.state = { data: [] }
}
loadCommentsFromServer() {
$.ajax({
....
}
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
}
You can do simply have another function for the POST
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With