By: @richardkotze
Fundamentals
import React, { Component } from 'react';
class Hello extends Component {
render() { // Required
return (
<div>Hello World!</div> //JSX
);
}
}
// JSX converted
React.createElement('div', null, 'Hello world!');
var React = require('react');
var Hello = React.createClass({
render: function(){ // Required
return (
<h1>Hello, world!</h1>
);
}
});
Classic/old way
// ES6
import { render } from 'react-dom';
// render component to the page
render(<Hello />,
document.getElementById('element-id'));
Render belongs to 'react-dom' module
class Hello extends Component {
render() {
return (
<h1>Hello, {this.props.word}!</h1>
);
}
};
return (
<Hello word="React" />
)
Set and access properties in a component
class Hello extends Component {
render() {
return (
<h1>Hello, {this.props.message}!</h1>
);
}
};
Hello.defaultProps = {
message: "World"
};
class Hello extends Component {
render() {
return (
<h1 className="add-class-name-here">
Hello, {this.props.word}!
</h1>
);
}
};
HTML class attr = JSX className attr
class Hello extends Component {
constructor(){
super();
this.state = {
message: "world!"
}
}
render() {
return (
<div>
Hello {this.state.message}
</div>
);
}
}
Initial state set in constructor
class Hello extends Component {
componentDidMount() {
this.setState({
message: "Mobile"
});
}
render() {
return (
<div>
Hello {this.state.message}
</div>
);
}
}
// ES6 function
const ActionBox = (props) => (
<div>
<p>Are you sure?</p>
<button data-action-id={props.actionId}>
{props.children}
</button>
</div>
);
Show: Destructing props - like pattern matching
class Hello extends Component {
componentWillMount() {
// run before mount
}
componentDidMount() {
// run after mount
}
componentWillUnmount() {
// run just before unmount
}
render() {
return (
<div>Hello world</div>
);
}
}
Different stages of component rendering
handleClickMe = () => { // fat arrow function
this.setState({
message: 'I was clicked'
});
}
render() {
return <button onClick={this.handleClickMe}>Click me</button>;
}
import MobileApp, { HintsByLocation } from 'mobile-app';
render() {
return (
<div>
<MobileApp>
<HintsByLocation />
</MobileApp>
</div>
);
}
import ComponentX from './component-x'; //ES6
class HelloComponent ...
export default HelloComponent; //ES6
primeNumbers = () => ...
export { ComponentX, primeNumbers } // list of items to export
Import to get a module
Export default - only one per module
Export objects
Basic components
<PhotoSlider />
<Image />
<Button.L />
<Button.R />
git clone git@github.com:rkotze/react-lib.git