Ok so because React is a front end framework you will not have access to things on your backend such as methods like db.collection.insert(). You will in tern has a separation of front end code and back end code. They will talk to each other through HTTP requests (GET, POST, PUT, DELETE).
Side note just to clarify. You will still need express for routing as well as react-router. They do different types of "routing". Express will handle routing of mainly your API, all the data calls that your front end will make to it. React-router handles page changes on your front end, right within the bowser. This keeps your page from reloading each time the user moves around.
So lets get into a little code.
On your back end you will need an express endpoint for your app to talk to. In this example I will show use with the package mongoose as it is a tool that is commonly used with a node.js backend.
https://www.npmjs.com/package/mongoose
var mongoose = require('mongoose');
var Message = require('../models/message');
app.post('/message', (req, res) => {
var newMessage = new Message(req.body);
newMessage.save((err, doc) => {
if (err) {
res.send(err);
} else {
res.send(doc);
}
});
});
This code will handle a post request at the url "/message". It will proceed to create a new message from the data in the request (req) body. Then save that to the database. After the save is successful it will send back the document that was just saved.
In mongoose we create a schema for each of our data models like such:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MessageSchema = new Schema({
content: {
type: String,
},
createdAt: {
type: Date,
default: Date.now
}
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
Now on the front end / React side of things we need to send our message data to the backend to save. We can use a package like axios to make clean promise based HTTP requests from the browser.
https://www.npmjs.com/package/axios
var NewMessageInput = React.createClass({
postMessage: function(value) {
axios.post('/message', {
content: value
})
.then(function (message) {
console.log(message);
})
},
render: function() {
return (
<div>
<input onSubmit={() => this.postMessage(value)}>Type your message here</input>
</div>
);
}
});
And that should do it!
For a backend example check out this repo I have setup. It's very basic but will be a good example of a backend with mongoose for reference.
https://github.com/Alexg2195/simple-dev-example
Also here is a bit of some side content I created for teaching React that may be a good reference.
https://github.com/Alexg2195/UT-ReactJS