Skip to content

Instantly share code, notes, and snippets.

View alexnm's full-sized avatar

Alex Moldovan alexnm

View GitHub Profile
@alexnm
alexnm / server.js
Created March 24, 2018 11:45
Server side render with react router in place
/* ... */
import { StaticRouter } from "react-router-dom";
/* ... */
app.get( "/*", ( req, res ) => {
const context = { };
const jsx = (
<StaticRouter context={ context } location={ req.url }>
<Layout />
</StaticRouter>
@alexnm
alexnm / server.js
Created March 24, 2018 07:49
Basic setup for React SSR
import express from "express";
import path from "path";
import React from "react";
import { renderToString } from "react-dom/server";
import Layout from "./components/Layout";
const app = express();
app.use( express.static( path.resolve( __dirname, "../dist" ) ) );
class ScrollPosition extends React.Component {
constructor( ) {
super( );
this.state = { position: 0 };
this.updatePosition = this.updatePosition.bind(this);
}
componentDidMount( ) {
window.addEventListener( "scroll", this.updatePosition );
}
function withAuthentication(WrappedComponent) {
const ModifiedComponent = (props) => {
if (!props.isAuthenticated) {
return <Redirect to="/login" />;
}
return (<WrappedComponent { ...props } />);
};
const mapStateToProps = (state) => ({
@alexnm
alexnm / hoc.jsx
Last active February 27, 2018 09:14
const withProps = ( newProps ) => ( WrappedComponent ) => {
const ModifiedComponent = ( ownProps ) => ( // the modified version of the component
<WrappedComponent { ...ownProps } { ...newProps } /> // original props + new props
);
return ModifiedComponent;
};
const Details = ( { name, title, language } ) => (
<div>
const Details = ( { name, language } ) => (
<div>
<p>{ name } works with { language }</p>
</div>
);
class Details extends React.Component {
render() {
const { name, language } = this.props;
return (
const Details = ( { name, language } ) => (
<div>
<p>{ name } works with { language }</p>
</div>
);
const Layout = ( { title, ...props } ) => (
<div>
<h1>{ title }</h1>
<Details { ...props } />
@alexnm
alexnm / conditional-bad.jsx
Created January 28, 2018 14:23
Bad example of conditional render
const condition = true;
const App = () => {
const innerContent = condition ? (
<div>
<h2>Show me</h2>
<p>Description</p>
</div>
) : null;
const condition = true;
const App = () => (
<div>
<h1>This is always visible</h1>
{
condition && (
<div>
<h2>Show me</h2>
<p>Description</p>
import expect from "expect.js";
import reducer from "./reducers";
import actions from "./actions";
describe( "duck reducer", function( ) {
describe( "quack", function( ) {
const quack = actions.quack( );
const initialState = false;
const result = reducer( initialState, quack );