Learning ReactJS and keeping track of it all
-
-
Save madkap/fe9d430ba48ffc05e65af66d4b47c63c to your computer and use it in GitHub Desktop.
Stuff about ReactJS itself
Your event handlers will be passed instances of SyntheticEvent
, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation()
and preventDefault()
, except the events work identically across all browsers.
If you find that you need the underlying browser event for some reason, simply use the nativeEvent
attribute to get it. Every SyntheticEvent
object has the following attributes:
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
DOMEventTarget target
number timeStamp
string type
Note:
As of v0.14, returning
false
from an event handler will no longer stop event propagation. Instead,e.stopPropagation()
ore.preventDefault()
should be triggered manually, as appropriate.
The SyntheticEvent
is pooled. This means that the SyntheticEvent
object will be reused and all properties will be nullified after the event callback has been invoked.
This is for performance reasons.
As such, you cannot access the event in an asynchronous way.
function onClick(event) {
console.log(event); // => nullified object.
console.log(event.type); // => "click"
var eventType = event.type; // => "click"
setTimeout(function() {
console.log(event.type); // => null
console.log(eventType); // => "click"
}, 0);
// Won't work. this.state.clickEvent will only contain null values.
this.setState({clickEvent: event});
// You can still export event properties.
this.setState({eventType: event.type});
}
Note:
If you want to access the event properties in an asynchronous way, you should call
event.persist()
on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
React normalizes events so that they have consistent properties across different browsers.
The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture
to the event name; for example, instead of using onClick
, you would use onClickCapture
to handle the click event in the capture phase.
Event names:
onCopy onCut onPaste
Properties:
DOMDataTransfer clipboardData
Event names:
onCompositionEnd onCompositionStart onCompositionUpdate
Properties:
string data
Event names:
onKeyDown onKeyPress onKeyUp
Properties:
boolean altKey
number charCode
boolean ctrlKey
boolean getModifierState(key)
string key
number keyCode
string locale
number location
boolean metaKey
boolean repeat
boolean shiftKey
number which
Event names:
onFocus onBlur
Properties:
DOMEventTarget relatedTarget
These focus events work on all elements in the React DOM, not just form elements.
Event names:
onChange onInput onSubmit
For more information about the onChange event, see Forms.
Event names:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
The onMouseEnter
and onMouseLeave
events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.
Properties:
boolean altKey
number button
number buttons
number clientX
number clientY
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
number pageX
number pageY
DOMEventTarget relatedTarget
number screenX
number screenY
boolean shiftKey
Event names:
onSelect
Event names:
onTouchCancel onTouchEnd onTouchMove onTouchStart
Properties:
boolean altKey
DOMTouchList changedTouches
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
boolean shiftKey
DOMTouchList targetTouches
DOMTouchList touches
Event names:
onScroll
Properties:
number detail
DOMAbstractView view
Event names:
onWheel
Properties:
number deltaMode
number deltaX
number deltaY
number deltaZ
Event names:
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted
onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay
onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend
onTimeUpdate onVolumeChange onWaiting
Event names:
onLoad onError
Event names:
onAnimationStart onAnimationEnd onAnimationIteration
Properties:
string animationName
string pseudoElement
float elapsedTime
Event names:
onTransitionEnd
Properties:
string propertyName
string pseudoElement
float elapsedTime
This module is pretty straightforward: You specify a set of requirements, and the children will be rendered if they are met. Also handles changes so if you resize or flip or whatever it all just works.
A MediaQuery element functions like any other React component, which means you can nest them and do all the normal jazz.
var MediaQuery = require('react-responsive');
var A = React.createClass({
render: function(){
return (
<div>
<div>Device Test!</div>
<MediaQuery query='(min-device-width: 1224px)'>
<div>You are a desktop or laptop</div>
<MediaQuery query='(min-device-width: 1824px)'>
<div>You also have a huge screen</div>
</MediaQuery>
<MediaQuery query='(max-width: 1224px)'>
<div>You are sized like a tablet or mobile phone though</div>
</MediaQuery>
</MediaQuery>
<MediaQuery query='(max-device-width: 1224px)'>
<div>You are a tablet or mobile phone</div>
</MediaQuery>
<MediaQuery query='(orientation: portrait)'>
<div>You are portrait</div>
</MediaQuery>
<MediaQuery query='(orientation: landscape)'>
<div>You are landscape</div>
</MediaQuery>
<MediaQuery query='(min-resolution: 2dppx)'>
<div>You are retina</div>
</MediaQuery>
</div>
);
}
});
To make things more idiomatic to react, you can use camelcased shorthands to construct media queries.
For a list of all possible shorthands and value types see https://github.com/wearefractal/react-responsive/blob/master/src/mediaQuery.js#L9
Any numbers given as a shorthand will be expanded to px (1234
will become '1234px'
)
var MediaQuery = require('react-responsive');
var A = React.createClass({
render: function(){
return (
<div>
<div>Device Test!</div>
<MediaQuery minDeviceWidth={1224}>
<div>You are a desktop or laptop</div>
<MediaQuery minDeviceWidth={1824}>
<div>You also have a huge screen</div>
</MediaQuery>
<MediaQuery maxWidth={1224}>
<div>You are sized like a tablet or mobile phone though</div>
</MediaQuery>
</MediaQuery>
<MediaQuery maxDeviceWidth={1224}>
<div>You are a tablet or mobile phone</div>
</MediaQuery>
<MediaQuery orientation='portrait'>
<div>You are portrait</div>
</MediaQuery>
<MediaQuery orientation='landscape'>
<div>You are landscape</div>
</MediaQuery>
<MediaQuery minResolution='2dppx'>
<div>You are retina</div>
</MediaQuery>
</div>
);
}
});
You may specify an optional component
property on the MediaQuery
that indicates what component to wrap children with. Any additional props defined on the MediaQuery
will be passed through to this "wrapper" component. If the component
property is not defined and the MediaQuery
has more than 1 child, a div
will be used as the "wrapper" component by default. However, if the component
prop is not defined and there is only 1 child, that child will be rendered alone without a component wrapping it.
Specifying Wrapper Component
<MediaQuery minDeviceWidth={700} component="ul">
<li>Item 1</li>
<li>Item 2</li>
</MediaQuery>
// renders the following when the media query condition is met
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
Unwrapped Component
<MediaQuery minDeviceWidth={700}>
<div>Unwrapped component</div>
</MediaQuery>
// renders the following when the media query condition is met
<div>Unwrapped component</div>
Default div Wrapper Component
<MediaQuery minDeviceWidth={1200} className="some-class">
<div>Wrapped</div>
<div>Content</div>
</MediaQuery>
// renders the following when the media query condition is met
<div className="some-class">
<div>Wrapped</div>
<div>Content</div>
</div>
// properties that match media queries
var matchers = {
orientation: PropTypes.oneOf([
'portrait',
'landscape'
]),
scan: PropTypes.oneOf([
'progressive',
'interlace'
]),
aspectRatio: PropTypes.string,
deviceAspectRatio: PropTypes.string,
height: stringOrNumber,
deviceHeight: stringOrNumber,
width: stringOrNumber,
deviceWidth: stringOrNumber,
color: PropTypes.bool,
colorIndex: PropTypes.bool,
monochrome: PropTypes.bool,
resolution: stringOrNumber
};
// media features
var features = {
minAspectRatio: PropTypes.string,
maxAspectRatio: PropTypes.string,
minDeviceAspectRatio: PropTypes.string,
maxDeviceAspectRatio: PropTypes.string,
minHeight: stringOrNumber,
maxHeight: stringOrNumber,
minDeviceHeight: stringOrNumber,
maxDeviceHeight: stringOrNumber,
minWidth: stringOrNumber,
maxWidth: stringOrNumber,
minDeviceWidth: stringOrNumber,
maxDeviceWidth: stringOrNumber,
minColor: PropTypes.number,
maxColor: PropTypes.number,
minColorIndex: PropTypes.number,
maxColorIndex: PropTypes.number,
minMonochrome: PropTypes.number,
maxMonochrome: PropTypes.number,
minResolution: stringOrNumber,
maxResolution: stringOrNumber
};
assign(features, matchers);
// media types
var types = {
all: PropTypes.bool,
grid: PropTypes.bool,
aural: PropTypes.bool,
braille: PropTypes.bool,
handheld: PropTypes.bool,
print: PropTypes.bool,
projection: PropTypes.bool,
screen: PropTypes.bool,
tty: PropTypes.bool,
tv: PropTypes.bool,
embossed: PropTypes.bool
};
var all = {};
assign(all, types);
assign(all, features);
// add the type property
assign(matchers, { type: Object.keys(types) });
module.exports = {
all: all,
types: types,
matchers: matchers,
features: features
};
Everything below is taken from react-router-tutorial
At its heart, React Router is a component.
// index.js
// ...
import { Router, Route, hashHistory } from 'react-router'
render((
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Router>
), document.getElementById('app'))
To have a shared Nav
we'd have to render Nav
component across each screen (think HTML old school way of doing shared nav). React Router provides another way to share UI with nested routes.
First, let the App Route have children, and move the other routes underneath it.
// index.js
// ...
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
{/* make them children of `App` */}
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
Next, render children inside of App.
// modules/App.js
// ...
render() {
return (
<div>
<h1>React Router Tutorial</h1>
<ul role="nav">
<li><Link to="/about">About</Link></li>
<li><Link to="/repos">Repos</Link></li>
</ul>
{/* add this */}
{this.props.children}
</div>
)
}
// ...
To show list of links for sub pages' nested menu add this.props.children
to the component
// index.js
// ...
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
// Repos.js
import NavLink from './NavLink'
// ...
<div>
<h2>Repos</h2>
<ul>
<li><NavLink to="/repos/reactjs/react-router">React Router</NavLink></li>
<li><NavLink to="/repos/facebook/react">React</NavLink></li>
</ul>
{/* will render `Repo.js` when at /repos/:userName/:repoName */}
{this.props.children}
</div>
One way that Link
is different from a
is that it knows if the path it links to is active so you can style it differently.
// activeStyle
<li><Link to="/about" activeStyle={{ color: 'red' }}>About</Link></li>
<li><Link to="/repos" activeStyle={{ color: 'red' }}>Repos</Link></li>
// activeClassName
<li><Link to="/about" activeClassName="active">About</Link></li>
<li><Link to="/repos" activeClassName="active">Repos</Link></li>
Create a Nav Link Component to have shared styles
// modules/NavLink.js
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})
// modules/App.js
import NavLink from './NavLink'
// ...
<li><NavLink to="/about">About</NavLink></li>
<li><NavLink to="/repos">Repos</NavLink></li>
Consider the following URLs:
/repos/reactjs/react-router
/repos/facebook/react
These URLs would match a route path like this:
/repos/:userName/:repoName
The parts that start with :
are URL parameters whose values will be parsed out and made available to route components on this.props.params[name]
.
Sample Route with params
<Route path="/repos/:userName/:repoName" component={Repo}/>
{/* ... */}
<Link to="/repos/reactjs/react-router">React Router</Link>
When we visit /
in this app it's just our navigation and a blank page. We'd like to render a Home
component there.
// index.js
// new imports:
// add `IndexRoute` to 'react-router' imports
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
// and the Home component
import Home from './modules/Home'
// ...
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
{/* add it here, as a child of `/` */}
<IndexRoute component={Home}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
Add a link to the Home
component using IndexLink
it will only be active when actually on the Home
page.
// App.js
import { IndexLink } from 'react-router'
// ...
<li><IndexLink to="/" activeClassName="active">Home</IndexLink></li>
onlyActiveOnIndex
Property
Remember, in NavLink
we're passing along all of our props to Link
with the {...spread}
syntax, so we can actually add the prop when we render a NavLink
and it will make its way down to the Link
:
<li><NavLink to="/" onlyActiveOnIndex={true}>Home</NavLink></li>
Using browserHistory
instead of hashHistory
to have a clean url without the #
. There needs to be some server configuration as well.
// index.js
// ...
// bring in `browserHistory` instead of `hashHistory`
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
render((
<Router history={browserHistory}>
{/* ... */}
</Router>
), document.getElementById('app'))
Need to configure server since the browser handles urls. The Webpack Dev Server has an option to enable this. Open up package.json and add --history-api-fallback.
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
We also need to change our relative paths to absolute paths in index.html since the URLs will be at deep paths and the app, if it starts at a deep path, won't be able to find the files.
<!-- index.html -->
<!-- index.css -> /index.css -->
<link rel="stylesheet" href="/index.css">
<!-- bundle.js -> /bundle.js -->
<script src="/bundle.js"></script>