Functional Components with React stateless functions and Ramda

  • A bit of functional programming (compose, curry, lenses)
  • A bit of React
  • A bit of ES6

What is a React stateless function?

App container

Stateless Timer component

const render = App.render(document.getElementById(‘app’));
(props) => ReactDOM.render(...)
setInterval(() => {
appState.secondsElapsed++;
render(appState);
}, 1000);
currentState -> newState
const secondsElapsedLens = R.lensProp('secondsElapsed');
  • View
R.view(secondsElapsedLens, { secondsElapsed: 10 });  //=> 10
  • Set
R.set(secondsElapsedLens, 11, { secondsElapsed: 10 });  //=> 11
  • Set by applying a given function
R.over(secondsElapsedLens, R.inc, { secondsElapsed: 10 });  //=> 11
const incSecondsElapsed = R.over(secondsElapsedLens, R.inc);
appState = incSecondsElapsed(appState);

Compose React stateless functions

  • A container
  • A list
  • And a list item
const TodoList = R.compose(Container, List, ListItem);
  • Mock some todos in the appState
let appState = {
secondsElapsed: 0,
todos: [
{id: 1, text: 'Buy milk'},
{id: 2, text: 'Go running'},
{id: 3, text: 'Rest'}
]
};
  • Import TodoList and add it as a child of the App component:
import TodoList from './todo-list';const App = appState => (<div className="container">
<h1>App name</h1>
<Timer secondsElapsed={appState.secondsElapsed} />
<TodoList todos={appState.todos} />
</div>);
<TodoList todos={appState.todos} />
TodoList({todos: appState.todos});
const TodoList = R.compose(Container, List, R.map(ListItem), R.prop('todos'));

--

--

--

Senior Software Engineer @ Citadel Milan LLC

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mirko Mariani

Mirko Mariani

Senior Software Engineer @ Citadel Milan LLC

More from Medium

White Screen of Death In React

JBook, CellList and custom hooks

Enhance your React components with TypeScript Records