Learning ReactJS

I’m learning ReactJS.  The JSX approach a bit different from the JavaScript & HTML that is familiar to me, and I have been tripping over the syntax and assumptions. Perhaps you can learn from my mistakes.

There are multiple acceptable ways to create a React component.

  • vanilla JavaScript: var ClassName = React.createClass({ ... })
  • ES6 class: class ClassName extends React.Component { ... }
  • ES6 arrow function: const ClassName = (props) => { /* render */ }

I chose the ES6 arrow function syntax for components that only have a render() method, and the React.createClass() syntax for all other components.

It took me some time to realize that React is managing DOM element objects and attributes, not HTML or fragments or strings. I tried to create an opening tag with its attributes in JSX, and its closing tag as a string. That did not work, because JSX created an element. Instead, I learned to compose elements from subcomponents. A component must render a DOM element/object … it does not want to return multiple siblings, unless they’re wrapped in a single DOM element (e.g. div, span, p).

I used ES6 syntax where advantageous, especially the default parameters, arrow functions, and spread/rest parameters. This only works if you have a ES6 pre-processor in your development environment. The solution I chose was to write the app on plnkr.co. You could use CodePen.io or JSFiddle.net just as well.

One last issue… attribute names. The first component I created was a LABEL. It only has 1 meaningful attribute “for”. Or so I thought. “for” is the deprecated shortcut for “htmlFor”, just like “class” is used for “className”. Both “for” and “class” are JavaScript reserved keywords, which may be why they are not supported in JSX. Anyway, I will never forget that “htmlFor” and “className” are the only exceptions to HTML attribute names.

These articles helped me the most in getting up and running with ReactJS:

Leave a Reply