angr

writings from zac anger, who is not all that angry

More React Notes

April 27, 2016 — Zac Anger

Lifecycle &Co.

  • The three phases of life:
    • Mounting
    • Updating
    • Unmounting
  • Mounting:
    • getInitialState(), before component is mounted.
    • componentWillMount(), immediately before mounting.
    • componentDidMount(), immediately after mounting. DOM-node-dependant initialisation happens here.
  • Updating:
    • componentWillReceiveProps(), invoked when mounted component receives new props from parent. Use this when changing state (this.setState()).
    • shouldComponentUpdate(), invoked when component 'decides' whether or not to push updates to the DOM. Return false from this if we don't want React to update.
    • componentDidUpdate(), invoked immediately after updating.
  • Unmounting:
    • componentWillUnmount(), immediately before component unmounts and is destroyed. Clean-up goes here.
  • While mounted, component.forceUpdate() is also available. This is for any mounted component whose state has changed without this.setState().

The big, big difference between props and state: state is private to components. A parent component (or any other component) can never manipulate the state of another (with setState or whatever).

  • So:
    • parent passes new props to child
    • child handles new props with componentWillReceiveProps
    • calls setState if necessary
    • child handles new state in componentWillUpdate
    • if component is stateful, componentWIllReceiveProps will be enough here

Defaults set in getInitialState will be used for initial rendering.

tags: react, lifecycle, events

so, tweet it?  

REACT NOTES

January 25, 2016 — Zac Anger

This is all such a mess, and so unsorted, so, sorry about that in advance.

This is also almost entirely notes from very early on in trying to learn React, so not all of it will be completely valid, probably. Okay. So.

Enjoy.

REACT NOTES (yeah, again):

There's no if...else in JSX. Doesn't work. Don't try it (in your JSX).

Don't try <!doctype> either. It'll break stuff.

Same with HTML comments. Not worth the trouble, I guess. No one reads them, anyway, so whatever.

Don't try to use your own code style. JSX needs to be written the way the docs say to. Doing React means doing React their way, so screw your purely stylistic preferences, they don't matter anymore. Which, unfortunately, means semicolons everywhere. Gross.

Every single XML tag needs to be closed. That means that <br> is invalid, but <br></br> is... totally valid. Also, self-closing tags (which literally do not even exist in HTML anymore) work just fine, so <div /> is valid. What the hell.

In JSX, everything in {} will be evaluated as Javascript. So you can do some things there, if you need to. (But not if...else!)

Any JSX over multiple lines needs to be wrapped in parens. If it's single-line, you don't need them.

Evidently it's better to indent all the stuff going in your tags just inside the tag, rather than even with the first whatchamacallit. This is what I mean:

<input type="text"
       value={whatever.stuff}
       onChange={this.foo.bar} />

...is apparently NOT the way to do it. Instead, we want to do:

<input
  type="text"
  value={whatever.stuff}
  onChange={this.foo.bar} />

which, personally, I find more annoying and less readable, but apparently that's how the React community does, so whatever. Oh, and as to the closing of the tag, no matter what it's gonna be hideous, so I don't know or care whether it should be on a newline. Probably not, because that's just even more lines, but I have seen a lot of this:

<input type="text"
  value={whatever.stuff}
  onChange={this.foo.bar}
/>

which is really even more annoying, but whatever. Lastly, as far as style goes, I'll just put what would make the most sense to me, personally. Note how clean and lined up things are? Yeah. Much better, to my eyes. Still ugly af, though.

<input type="text"
      value={whatever.stuff}
   onChange={this.foo.bar} />

read more...

tags: react, webpack, js, notes, redux

so, tweet it?  

Isomorphic Apps in React

January 25, 2016 — Zac Anger

I don't know for sure that this deserves its own file... we'll see.

We'll be processing several requests simultaneously, so we should deal with a global state (dependent on user) (like flux stores state, or whatever).

About 90%, really, of the client and server code, should be shared.

Which parts should be isomorphic?

  1. view
  2. styles
  3. routing
  4. data fetching
  5. config
  6. i10n

The view is already there, really. Just gotta use ReactDOM.renderToString instead of ReactDOM render.

Inline styles better than individual sheets in the dirs, for this architecture. React supports them. That said, one should emulate pseudo attributes (:hover, :active, and :focus, for example) in your Javascript. Handle your own prefixes (grooosss). Emulate your media queries in Js, too. Gotta eventually merge the CSS somehow; http://stack.formidable.com/radium/ isn't half-bad for that.

Because there's so much Js to bundle up and load, it's actually okay to but the bundle at the end of your markup for this case. But we want to split things out in the webpack.config.js, so that we've got CSS on its own and can load that first the way we used to. Here's a sample webpack.config.js:

var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry: "./src/app.js",
  plugins: [
    new webpackDefinePlugin({
      "process.env": {
        BROWSER: JSON.stringify(true),
        NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
      }
    }),
    new ExtractTextPlugin("[name].css")
  ],
  output : {
    path: __dirname + '/public/build/',
    filename: 'bundle.js',
    publicPath: 'build/'
  },
  module: {
    loaders: [
      {
        test: /\.css%/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader")
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!less-loader")
      },
      {
        test: /\.png$/,
        loader: "url-loader?limit=10000&mimietype=image/png"
      },
      {
        test: /\.jsx$/,
        loader: "react-hot!babel!eslint-loader",
        exclude: [/node_modules/, /public/]
      },
      {
        test: /\.js$/,
        loader: "babel!eslint-loader",
        exclude: [/node_modules/, /public/]
    ]
  },
  eslint: {
    configFile: '.eslintr`^c'
  }
}

React Router works well for isomorphic stuff. Here's an example of using it with server-side rendering:

import {renderToString} from 'react-dom/server'
import {match, RouterContext} from 'react-router'
import routes from './routes'

serve((req, res) =>
  // req.url would be full url path from original request, including query string
    match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
      if (error){res.status(500).send(error.message)}
      else if (redirectLocation){res.redirect(302, redirectLocation.pathname + redirectLocation.search)}
      else if (renderProps){res.status(200).send(renderToString(<RouterContext {...renderProps} />))}
      else {res.status(404).send('404 not found')}
  })
)

Redux in an isomporhic app: better than a singelton flux store. With Redux we can use react-redux's react context. Using redux store's API makes dumping and restoring store state easy. Check the code of https://github.com/WebbyLab/itsquiz-wall for a really good, in-depth, production app using all of the above tech in an isomorphic app.

Here's a simple api example that works both server- and client-side:

'use strict'
import apiFactory from './api'

const api=apiFactory({
  apiPrefix: 'http://pharoah.js.org/api/v1'
})
const promise = api.users.list()

Here's a promise-pased client: https://www.npmjs.com/package/axios

Here are two that use Fetch (which are fine in Mozilla and Chromium, now): https://www.npmjs.com/package/isomorphic-fetch and https://www.npmjs.com/package/node-fetch

So, here's what we might do on the client:

  • render react components
  • show spinners
  • fetch component-dependent data
  • update the page

And on the server:

  • preload all the data
  • render the page to a string
  • send html to the client

How to do this isomorphically? Check that itsquiz app again, it's so much easier than typing out an example here.

For a full-on tutorial using React and Redux to make an isomorphic app (Todos, of course...), check here: https://medium.com/front-end-developers/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4

tags: isomorphic, react, js

so, tweet it?  

meteor and react

January 21, 2016 — Zac Anger

anything in <template>is a _meteor_ template</template>; include in html by {{> thatTemplate}}, or in js with Template.thatTemplate. (not doing that at all with react as view.)

React.createClass defines a new view... class. why are components classes? props are attributes that allow compnents/classes to inherit data.

render() (react) gets a description of the markup to show. html's inside jsx, so get used to angle brackets in your scripting, yay.... jsx: className instead of class. jsx, not templating lang... just compiles to plain old js.

jsx can use es6 (what about esnext-next?). this includes const & let, methodShorthand(){...}, and =>.

collections: how meteor stores persistent data. aka mongo. lol duh. accessible from server and client.

collectionName = new Mongo.Collection("collection-name") to make that happen. that makes a new mongo collection on the server, and cache on the client.

tags: meteor, react, js

so, tweet it?  

Notes

January 13, 2016 — Zac Anger

So, I have a lot of notes that I've taken over the course of the last couple of months. Seeing as they're not doing me a whole lot of good sitting in a pile of Markdown files, I'm gradually going through them, cleaning them up, and I think I'll just post them all as sort of blog posts. Why not? So here's a little list of the topics I'll be covering over the next few weeks:

  • Unicode
  • SystemJS (and JSPM)
  • Go
  • UI
  • Github Organizations
  • Functional Reactive Programming (and RxJS)
  • Elm
  • Browserify
  • Bash Builtins
  • Firebase
  • ES6
  • Pusher
  • Styleguides
  • Passport (and problems getting errors out of Express)
  • React (and Webpack)
  • Isomorphic React
  • Flux
  • Meteor
  • All the reasons I kind of dislike Angular
  • Bacon.js
  • Basics of webmastering (which is totally not a word)
  • Functional programming (in general)
  • Effective web design
  • Mongo (and Mongoose, and MongoJS, and Mongolayer)
  • Ruby, maybe a little bit
  • Electron (formerly Atom Shell)
  • NW.js (formerly Node Webkit)
  • Gulp
  • Node in general
  • Probably a good bit of Node stuff, really
  • I like Node a lot
  • Maybe a little bit of jQuery?
  • The developer hiring process
  • Maybe a little bit of that Javascript language, or something?
  • Probably not much at all on HTML, because HTML doesn't need... notes... really
  • CSS... lol, CSS.
  • People, and the experience of dealing with people on a regular basis
  • What it's like to live with the people I live with
  • What it's like to actually find myself liking human beings, and wanting to be around them, especially certain ones, quite a lot. (It's weird!)

tags: blogs, personal, notes, education, react, js, electron, flux, meteor, elm, gulp, css, es6, ruby, mongo, bash, unicode, go, ui, design

so, tweet it?  

My Problem With React

December 28, 2015 — Zac Anger

There's this post kinda making the rounds lately. It's a nice post. Everything in there, I agree with, for sure. Especially as someone who feels a lot more comfortable with Node than with, say, Angular's mostly ungrokable API. I get why people like React. I get React. It's not exactly hard to pick up, anyway. It's very logical and intuitive. And I really do like the concepts behind React. But I still have problems with it.

read more...

tags: react, frameworks, libraries, riot, vue, js, javascript, angular, components, jsx, mithril, design

so, tweet it?  

QUICK LITTLE THING

November 21, 2015 — Zac Anger

DevMountain Sign

read more...

tags: react, angular, mean-stack, meteor, socket, idk, personal projects, break

so, tweet it?  

React Meetup, 17 Nov, 2015

November 17, 2015 — Zac Anger

React: - Good at managing state. - which is to say, dynamism - Components, just like... everything else these days, so that's totally irrelevant. - virtual dom, which is not exactly facebook's anyway. - unidirectional data flow, which is a mouthful. - that is, the loop. - more boilerplate to run that... less boilerplate-replacer built into react?

read more...

tags: react, meetup, php, xml, js, school, meteor

so, tweet it?  

zac anger?