Skip to content

Instantly share code, notes, and snippets.

@hoolymama
Last active March 18, 2024 09:15
Show Gist options
  • Save hoolymama/99a65d22334a15e1235e5687c6b23c38 to your computer and use it in GitHub Desktop.
Save hoolymama/99a65d22334a15e1235e5687c6b23c38 to your computer and use it in GitHub Desktop.
Provide runtime environment to app made with create-react-app
import React, { Component } from "react";
import Navigation from "./Navigation";
import withConfig from "./withConfig";
class App extends Component {
componentWillMount() {
console.log(this.props.config);
}
render() {
const {config} = this.props;
return <Navigation someVar={config.SOME_VAR} />
}
}
export default withConfig(App);
{
"name": "myapp",
"version": "1.0.0",
"author": "Julian Mann",
"dependencies": {
"express": "^4.15.3",
"react": "^15.6.1",
"react-addons-css-transition-group": "^15.6.0",
"react-dom": "^15.6.1"
},
"devDependencies": {
"ava": "^0.20.0",
"proxyquire": "^1.8.0",
"react-scripts": "1.0.7"
},
"scripts": {
"start": "node server.js",
"dev": "PORT=8080 react-scripts start",
"build": "react-scripts build"
},
"engines": {
"node": ">=4.3.2"
},
"proxy": "http://localhost:5000"
}
const express = require("express");
const path = require("path");
const app = express();
var config = {
API_URL: process.env.API_URL || "http://api.somesite.com",
SOME_VAR: process.env.SOME_VAR || "some-value"
};
app.use(express.static(path.join(__dirname, "build")));
app.get("/config", function(req, res) {
res.json(config);
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
let server = app.listen(process.env.PORT || "5000", () => {
console.log("App listening on port %s", server.address().port);
console.log("Press Ctrl+C to quit.");
});
import React, { Component } from "react";
function withConfig(WrappedComponent) {
return class extends Component {
constructor(props) {
super(props);
this.state = {};
fetch("/config")
.then(res => res.json())
.then(data => {
this.state = data;
})
.catch(function() {
console.log("Cant reach server");
});
}
render() {
return <WrappedComponent {...this.props} config={this.state} />;
}
};
}
export default withConfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment