Rendering FrintJS Apps with React.js in the Browser and Server

Rendering FrintJS Apps with React.js in the Browser and Server

  • Rendering FrintJS Apps with React.js in the Browser and ServerI spent more time on this image than writing this post =DPreviously, I wrote about dependency injection and how providers are set up in FrintJS Apps.
  • Today, we will be using the same APIs and render a FrintJS App with React in the browser and server.Rendering with react-domIn the most basic and simple example, we can render a React component like this using ReactDOM:import React from ‘react’;import { render } from ‘react-dom’;function MyComponent() { return pHello…
  • /p;}const App = createApp({ name: ‘MyApp’, providers: [ { name: ‘component’, useValue: MyComponent, }, ],});It is by convention that we set the React component as a provider by giving it the name component.The same convention applies for our Vue.js, React Native, and Preact integrations too, as they can be found…
  • Only difference is that instead of receiving a Component as its first argument, it receives our App’s instance.What about server-side rendering?We have it covered already with our frint-react-server package:import { renderToString } from ‘frint-react-server’const App = createApp({ … });const app = new App();const html = renderToString(app);This also follows similar API…
  • Think of it similar to how Redux does it with their Provider / component and connect higher-order component.This gives developers a lot of flexibility when they need to access certain providers for example, without having to keep passing them as props everywhere.I will follow up by writing another post soon…

Previously, I wrote about dependency injection and how providers are set up in FrintJS Apps. Today, we will be using the same APIs and render a FrintJS App with React in the browser and server. We…
Continue reading “Rendering FrintJS Apps with React.js in the Browser and Server”

JavaScript ES 2017: Learn Async/Await by Example – codeburst

  • Consider the below code:function doubleAfter2Seconds(x) { return new Promise(resolve = { setTimeout(() = { resolve(x * 2); }, 2000); });}In this code we have a function called doubleAfter2Seconds.
  • Here’s what the boilerplate code looks like:function addPromise(x){ return new Promise(resolve = { // Code goes here… // resolve() });}Awesome.
  • In this example we should be returning x + 2*a + 2*b + 2*c. Here’s the code:function addPromise(x){ return new Promise(resolve = { = { = { = { resolve(x + a + b + c); }) }) }) });}Lets walk through the code again, line by line.First, we create…
  • Here’s what that looks like:async function addAsync(x) { // code here…}Now that you’ve created an async function, we can make use of the await keyword which will pause our code until the Promise has resolved.
  • Here’s how easy that is:async function addAsync(x) { const a = await doubleAfter2Seconds(10); const b = await doubleAfter2Seconds(20); const c = await doubleAfter2Seconds(30); return x + a + b + c;}And here’s the full code:As you can see, we’re still making use of the same doubleAfter2Seconds function.

ES 2017 introduced Asynchronous functions. Async functions are essentially a cleaner way to work with asynchronous code in JavaScript. In order to understand exactly what these are, and how they work…
Continue reading “JavaScript ES 2017: Learn Async/Await by Example – codeburst”

React Native + Vue.js = React-Vue () This is so awesome! #react #vuejs

  • React-Vue is designed to connect React and Vue.
  • Thanks to Vue’s clear hierarchical design, we can easily pull out the reactivity system (9 KB gzipped), and drive React component rendering.
  • Introduce react-vue-loader, which compile the Vue component into a React component.
  • As you might think, your previously written Vue components can run inside the React component, and your React components can also run inside the Vue component.
  • All React Native Components exists as built-in components in Vue, you can use react native components as following

    The similar JSX code is as follows

react-vue – Run Vue in React and React Native
Continue reading “React Native + Vue.js = React-Vue () This is so awesome! #react #vuejs”

Using RxJS with React.js: Part 3 — Dispatching events from Component

Using RxJS with React.js: Part 3 - Dispatching events from Component

  • Using RxJS with React.js: Part 3 — Dispatching events from ComponentThis is the third part of the series.Illustration of unidirectional flow between Subject and ComponentUnidirectional cycleEarlier we saw an example of HoC streaming props to the base component.
  • Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will then be streamed back to the component completing one unidirectional cycle.We can take the example of a form input field.
  • To keep things simple, let’s say BehaviorSubject is a kind of Subject, that can already start with an initial value.import { BehaviorSubject } from ‘rxjs’;const subject$ = new = console.log(x)); // prints `foo` right awayThe base Component with form inputLet’s say this is our base component:import React from ‘react’const MyComponent = React.createClass({ render() { const { value, handleChange } = this.props; return ( div input type=”text” value={value} onChange={e = handleChange(e.target.value)} / pCurrent value: {value}/p /div ); }});From the base component, we are accessing the props value and handleChange.
  • First one is a stream of the input value, and the latter for handling the change.import { BehaviorSubject, Observable } from ‘rxjs’;const formInput$ = new BehaviorSubject(‘foo’); // with initial valueconst handlers$ = Observable.of({ handleChange: value = formInput$.
  • scan(function (props, emitted) { return { …props, …emitted }; });Observing the base ComponentNow that we have the props$ observable ready, we can integrate it with our base complement easily using the observe function from FrintJS:import { observe } from ‘frint-react’;const ObservedRoot = observe(function () { return props$;})(MyComponent);Now you can stream the props, including both the input value and the change handler from your HoC, and also trigger changes in the Subject from your Component’s events.Live demoVisit this example in JSBin.

Earlier we saw an example of HoC streaming props to the base component. Let’s now look at ways how we can dispatch events from inside the base component, update some value, and the updated value will…
Continue reading “Using RxJS with React.js: Part 3 — Dispatching events from Component”

How to build a React-Redux application with API-first CMS Contentful

How to build a #ReactJS #Redux application with API-first CMS Contentful:  #JavaScript

  • js with the followingreturn ( div{this.props.children}/div );Now go to the browser, refresh the page and see the changes.Fetch blog contentsNext we’ll integrate with Contentful so we can fetch and show blog posts dynamically.Steps to setup your Contentful accountSignup at Contentful (you can choose Free package, that will be sufficient for now) and create an empty space.Create a new Content Type and add few fields to it.
  • js file and use axios to make a GET request to Contentful server.import axios from ‘axios’;export const FETCH_POSTS = ‘FETCH_POSTS’;const API_BASE_URL = API_SPACE_ID = ‘buyxxxxxxx’;const API_TOKEN = function fetchPosts() { const request = return { type: FETCH_POSTS, payload: request };}fetchPosts action creator will return an action , which is nothing but a plain JavaScript object with a type property.
  • /actions/index’;const INITIAL_STATE = { all: [] };export default function(state = INITIAL_STATE, action) { switch(action.type) { case FETCH_POSTS: return { …state, all: action.payload.data.items }; default: return state; }}Next we will update the application state in .
  • /posts_reducer’;const rootReducer = combineReducers({ posts: PostsReducer});export default rootReducer;Displaying postsTo get our app working, now we’ll promote the PostsIndex component to a Redux container in .
  • /actions/index’;class PostsIndex extends Component { componentWillMount() { this.props.fetchPosts(); } renderPosts() { return this.props.posts.map((post, index) = { return ( article key={post.sys.id} h3{post.fields.title}/h3 p{post.fields.description}/p /article ); }); } render() { return ( div h2Blog Posts/h2 {this.renderPosts()} /div ); }}function mapStateToProps(state) { return { posts: state.posts.all };}export default connect(mapStateToProps, { fetchPosts })(PostsIndex);Then go to the browser, refresh the page and check the results.Now the existing UI may look very dull, only few headlines followed by some paragraphs.

When I first started to re-design my company website I was very excited to use ReactJS to build the front-end application in the React way. But soon I realised, in the excitement of using the new JS…
Continue reading “How to build a React-Redux application with API-first CMS Contentful”

Reducing React jank with (possibly hacky) use of WeakMap

Reducing React jank with (possibly hacky) use of WeakMap  #reactjs #javascript

  • You’ve heard that React’s Virtual DOM implement will help keep your UI snappy and snappy UI is exactly what will give your customers a warm happy glow inside.You’ve just written the first version of your code to test out your ideas:class List extends PureComponent { onClick () { //… } onUpdate (item, updatedValue) { //… } onMouseOver (item) { //… } render () { return ( div onClick={() = this.onClick()} { this.props.items.map((item) = ( Item key={item.id} item={item} onMouseOver={() = this.onMouseOver(item)} onUpdate={(value) = this.onUpdate(item, value)} / )) } /div ) }}class Item extends PureComponent { render () { const { item, onUpdate, …rest } = this.props return ( div {…rest} input type=”text” value={item.value} onChange={(e) = onUpdate(e.target.value)} / /div ) }}You know that React creates a representation of your components and uses it to efficiently update the browser when you provide a new version of this view.You understand that, whilst its generally more than sufficient in most cases, in some cases you want to improve the performance by using PureComponents to tell React which parts have not changed.You’ve put in the key attribute for all your items, which should give a hint to React as to which items match to which.You’ve used ImmutableJS for your state so the shallow compare algorithm that PureComponent uses will be fast and efficient.However you find that its still not helping, and every update still takes longer than you think it should.sooooo slowTo help you debug, you’ve installed the React DevTools for Chrome / Firefox.You click on the little checkbox on the top left corner called ‘Trace React Updates’, which will flash a border around any component that was just updated.With this feature switched on, you notice that, even though you’ve been a good little front-end developer and have done all the performance best practices, each Item is still being updated every time you type.Not what was expectedYou expected that only the Item thats changed should have a flashing border.You search the internet for information and realise, “Duh I’m creating a new function every time I re-render List, even though the item itself didn’t change”.
  • You start by changing the `onClick` handler for the `List` componentclass List extends PureComponent { constructor () { this.onClick = this.onClick.bind(this) } onClick () { //… } //… render () { return ( div onClick={this.onClick} //… /div ) }}Better yet, you remembered there’s the class instance fields proposal, which allows you to define your onClick handler as an arrow function!
  • What to do…You could refactor the Item component so that every event handler is given the item as one of the arguments:class List extends PureComponent { //… render () { return ( div onClick={this.onClick} { this.props.items.map((item) = ( Item key={item.id} item={item} onMouseOver={(e, item) = this.onMouseOver(item)} onUpdate={(item, value) = this.onUpdate(item, value)} / )) } /div ) }}class Item extends PureComponent { render () { const { item, onMouseOver, onUpdate, …rest } = this.props return ( div onMouseOver={(e) = onMouseOver(e, item)} {…rest} input type=”text” onChange={(e) = onUpdate(item, e.target.value)} value={item.value} / /div ) }}Whilst this feels okay for the onUpdate handler, it feels wrong wrapping every possible DOM event handler that the consumer of your Item component could possibly need.You try another approach.
  • This way, only when an item has not been seen before will a new function reference be created:class List extends PureComponent { itemEventHandlers = new WeakMap() getItemEventHandler = (item) { return } const eventHandlers = { onUpdate: (value) = { //… }, onMouseOver: () = { //… } } eventHandlers) return eventHandlers } //… render () { return ( div onClick={this.onClick} { this.props.items.map((item) = ( Item key={item.id} item={item} / )) } /div ) }}You use a WeakMap so you don’t have to manually track when an item is no longer needed and thus its corresponding functions can be garbage collected.
  • Ah the beauty of weak references.You think, “Hey, why not just store the whole Item component instead of just the event handlers so the render function of the List component is even more efficient”:class List extends PureComponent { itemCache = new WeakMap() renderItemComponent = (item) { if(this.itemCache.has(item)){ return this.itemCache.get(item) } const component = ( Item key={item.id} item={item} onUpdate={(value) = {}} onMouseOver={() = {}} / ) this.itemCache.set(item, component) return component } onClick = () { //… } render () { return ( div onClick={this.onClick} { } /div ) }}Your code now does what you expect it to; Each Item updating only if its item has changed.When you go to check React DevTools though, all the `Item` components are still flashing.It works fast now, but DevTools still not showing what you expect.Looking closer, you notice that only the inner icon for the component you’ve changed blinks.

Say you’re building a new application. This application is going to be the thing that updates your company’s product experience to the latest and greatest. You/your designers have mocked up an…
Continue reading “Reducing React jank with (possibly hacky) use of WeakMap”

Just for Flask & React.js Developers: A New Neo4j Movies Template

Just for #Flask & #Reactjs Developers: A New #Neo4j Movies Template


via @thesilverlogic

  • The app submits a request to the register endpoint when a user fills out the “Create an Account” form and taps “Create Account”.
  • The app submits a request to the login endpoint when a user fills a username and password and taps “Create Account”.
  • The user is then directed to an authentication page, from which they can navigate through the app, view their user profile and rate movies.
  • Below is a rather empty user profile for a freshly created user:

    Once a user has logged in and navigated to a page that displays movies, the user can select a star rating for the movie or remove the rating of a movie he or she has already rated.

  • The user should be able to access their previous ratings (and the movies that were rated) both on their user profile and the movie detail page in question.

Discover this new movies template app designed for Python and JavaScript developers using Flask and React.js alongside the Neo4j graph database.
Continue reading “Just for Flask & React.js Developers: A New Neo4j Movies Template”