path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
index.android.js
octopitus/RNAnimatedBarChart
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import ChartContainer from './src/ChartContainer' export default class RNBarChart extends Component { render() { return <ChartContainer />; } } AppRegistry.registerComponent('RNBarChart', () => RNBarChart);
app/js/typer.js
mattiaslundberg/typer
import React from 'react' import Input from './components/input' import StatusDisplay from './components/status-display' import ResultDisplay from './components/result-display' export default class Typer extends React.Component { constructor(props) { super(props) this.state = { typedSequence: "", charsTyped: 0, } this.onType = this.onType.bind(this) } onType(evt) { if ( evt.keyCode == 16 || evt.keyCode == 9 || evt.getModifierState("Fn") || evt.getModifierState("Hyper") || evt.getModifierState("OS") || evt.getModifierState("Super") || evt.getModifierState("Win") ) { evt.preventDefault() return } if (this.state.charsTyped == 0) { this.setState({startedTyping: new Date().getTime()}) } if (evt.target.value == this.props.fullText.join("") && !this.state.finished) { this.setState({finished: new Date().getTime()}) } this.setState({ typedSequence: evt.target.value, charsTyped: this.state.charsTyped + 1 }) } render() { if (this.state.finished) { const milliseconds = this.state.finished - this.state.startedTyping const writtenChars = this.props.fullText.length return ( <div className="typer"> <ResultDisplay time={milliseconds} textLength={writtenChars} onNewClick={this.props.onNewClick} /> </div> ) } return ( <div className="typer"> <StatusDisplay typedSequence={this.state.typedSequence} fullText={this.props.fullText} startTime={this.state.startedTyping} /> <Input onType={this.onType} /> </div> ) } }
src/components/stories/Icon.js
radekzz/netlify-cms-test
import React from 'react'; import { Icon } from '../UI'; import { storiesOf } from '@kadira/storybook'; const style = { width: 600, margin: 20, fontSize: 30 }; storiesOf('Icon', module) .add('Default View', () => ( <div style={style}> <Icon type="bold"/> <Icon type="italic"/> <Icon type="list"/> <Icon type="font"/> <Icon type="text-height"/> <Icon type="text-width"/> <Icon type="align-left"/> <Icon type="align-center"/> <Icon type="align-right"/> <Icon type="align-justify"/> <Icon type="indent-left"/> <Icon type="indent-right"/> <Icon type="list-bullet"/> <Icon type="list-numbered"/> <Icon type="strike"/> <Icon type="underline"/> <Icon type="table"/> <Icon type="superscript"/> <Icon type="subscript"/> <Icon type="header"/> <Icon type="h1"/> <Icon type="h2"/> <Icon type="paragraph"/> <Icon type="link"/> <Icon type="unlink"/> <Icon type="quote-left"/> <Icon type="quote-right"/> <Icon type="code"/> <Icon type="picture"/> <Icon type="video"/> <Icon type="note"/> <Icon type="note-beamed"/> <Icon type="music"/> <Icon type="search"/> <Icon type="flashlight"/> <Icon type="mail"/> <Icon type="heart"/> <Icon type="heart-empty"/> <Icon type="star"/> <Icon type="star-empty"/> <Icon type="user"/> <Icon type="users"/> <Icon type="user-add"/> <Icon type="video"/> <Icon type="picture"/> <Icon type="camera"/> <Icon type="layout"/> <Icon type="menu"/> <Icon type="check"/> <Icon type="cancel"/> <Icon type="cancel-circled"/> <Icon type="cancel-squared"/> <Icon type="plus"/> <Icon type="plus-circled"/> <Icon type="plus-squared"/> <Icon type="minus"/> <Icon type="minus-circled"/> <Icon type="minus-squared"/> <Icon type="help"/> <Icon type="help-circled"/> <Icon type="info"/> <Icon type="info-circled"/> <Icon type="back"/> <Icon type="home"/> <Icon type="link-alt"/> <Icon type="attach"/> <Icon type="lock"/> <Icon type="lock-open"/> <Icon type="eye"/> <Icon type="tag"/> <Icon type="bookmark"/> <Icon type="bookmarks"/> <Icon type="flag"/> <Icon type="thumbs-up"/> <Icon type="thumbs-down"/> <Icon type="download"/> <Icon type="upload"/> <Icon type="upload-cloud"/> <Icon type="reply"/> <Icon type="reply-all"/> <Icon type="forward"/> <Icon type="quote"/> <Icon type="code-alt"/> <Icon type="export"/> <Icon type="pencil"/> <Icon type="feather"/> <Icon type="print"/> <Icon type="retweet"/> <Icon type="keyboard"/> <Icon type="comment"/> <Icon type="chat"/> <Icon type="bell"/> <Icon type="attention"/> <Icon type="alert"/> <Icon type="vcard"/> <Icon type="address"/> <Icon type="location"/> <Icon type="map"/> <Icon type="direction"/> <Icon type="compass"/> <Icon type="cup"/> <Icon type="trash"/> <Icon type="doc"/> <Icon type="docs"/> <Icon type="doc-landscape"/> <Icon type="doc-text"/> <Icon type="doc-text-inv"/> <Icon type="newspaper"/> <Icon type="book-open"/> <Icon type="book"/> <Icon type="folder"/> <Icon type="archive"/> <Icon type="box"/> <Icon type="rss"/> <Icon type="phone"/> <Icon type="cog"/> <Icon type="tools"/> <Icon type="share"/> <Icon type="shareable"/> <Icon type="basket"/> <Icon type="bag"/> <Icon type="calendar"/> <Icon type="login"/> <Icon type="logout"/> <Icon type="mic"/> <Icon type="mute"/> <Icon type="sound"/> <Icon type="volume"/> <Icon type="clock"/> <Icon type="hourglass"/> <Icon type="lamp"/> <Icon type="light-down"/> <Icon type="light-up"/> <Icon type="adjust"/> <Icon type="block"/> <Icon type="resize-full"/> <Icon type="resize-small"/> <Icon type="popup"/> <Icon type="publish"/> <Icon type="window"/> <Icon type="arrow-combo"/> <Icon type="down-circled"/> <Icon type="left-circled"/> <Icon type="right-circled"/> <Icon type="up-circled"/> <Icon type="down-open"/> <Icon type="left-open"/> <Icon type="right-open"/> <Icon type="up-open"/> <Icon type="down-open-mini"/> <Icon type="left-open-mini"/> <Icon type="right-open-mini"/> <Icon type="up-open-mini"/> <Icon type="down-open-big"/> <Icon type="left-open-big"/> <Icon type="right-open-big"/> <Icon type="up-open-big"/> <Icon type="down"/> <Icon type="left"/> <Icon type="right"/> <Icon type="up"/> <Icon type="down-dir"/> <Icon type="left-dir"/> <Icon type="right-dir"/> <Icon type="up-dir"/> <Icon type="down-bold"/> <Icon type="left-bold"/> <Icon type="right-bold"/> <Icon type="up-bold"/> <Icon type="down-thin"/> <Icon type="left-thin"/> <Icon type="right-thin"/> <Icon type="up-thin"/> <Icon type="ccw"/> <Icon type="cw"/> <Icon type="arrows-ccw"/> <Icon type="level-down"/> <Icon type="level-up"/> <Icon type="shuffle"/> <Icon type="loop"/> <Icon type="switch"/> <Icon type="play"/> <Icon type="stop"/> <Icon type="pause"/> <Icon type="record"/> <Icon type="to-end"/> <Icon type="to-start"/> <Icon type="fast-forward"/> <Icon type="fast-backward"/> <Icon type="progress-0"/> <Icon type="progress-1"/> <Icon type="progress-2"/> <Icon type="progress-3"/> <Icon type="target"/> <Icon type="palette"/> <Icon type="list"/> <Icon type="list-add"/> <Icon type="signal"/> <Icon type="trophy"/> <Icon type="battery"/> <Icon type="back-in-time"/> <Icon type="monitor"/> <Icon type="mobile"/> <Icon type="network"/> <Icon type="cd"/> <Icon type="inbox"/> <Icon type="install"/> <Icon type="globe"/> <Icon type="cloud"/> <Icon type="cloud-thunder"/> <Icon type="flash"/> <Icon type="moon"/> <Icon type="flight"/> <Icon type="paper-plane"/> <Icon type="leaf"/> <Icon type="lifebuoy"/> <Icon type="mouse"/> <Icon type="briefcase"/> <Icon type="suitcase"/> <Icon type="dot"/> <Icon type="dot-2"/> <Icon type="dot-3"/> <Icon type="brush"/> <Icon type="magnet"/> <Icon type="infinity"/> <Icon type="erase"/> <Icon type="chart-pie"/> <Icon type="chart-line"/> <Icon type="chart-bar"/> <Icon type="chart-area"/> <Icon type="tape"/> <Icon type="graduation-cap"/> <Icon type="language"/> <Icon type="ticket"/> <Icon type="water"/> <Icon type="droplet"/> <Icon type="air"/> <Icon type="credit-card"/> <Icon type="floppy"/> <Icon type="clipboard"/> <Icon type="megaphone"/> <Icon type="database"/> <Icon type="drive"/> <Icon type="bucket"/> <Icon type="thermometer"/> <Icon type="key"/> <Icon type="flow-cascade"/> <Icon type="flow-branch"/> <Icon type="flow-tree"/> <Icon type="flow-line"/> <Icon type="flow-parallel"/> <Icon type="rocket"/> <Icon type="gauge"/> <Icon type="traffic-cone"/> <Icon type="cc"/> <Icon type="cc-by"/> <Icon type="cc-nc"/> <Icon type="cc-nc-eu"/> <Icon type="cc-nc-jp"/> <Icon type="cc-sa"/> <Icon type="cc-nd"/> <Icon type="cc-pd"/> <Icon type="cc-zero"/> <Icon type="cc-share"/> <Icon type="cc-remix"/> <Icon type="github"/> <Icon type="github-circled"/> <Icon type="flickr"/> <Icon type="flickr-circled"/> <Icon type="vimeo"/> <Icon type="vimeo-circled"/> <Icon type="twitter"/> <Icon type="twitter-circled"/> <Icon type="facebook"/> <Icon type="facebook-circled"/> <Icon type="facebook-squared"/> <Icon type="gplus"/> <Icon type="gplus-circled"/> <Icon type="pinterest"/> <Icon type="pinterest-circled"/> <Icon type="tumblr"/> <Icon type="tumblr-circled"/> <Icon type="linkedin"/> <Icon type="linkedin-circled"/> <Icon type="dribbble"/> <Icon type="dribbble-circled"/> <Icon type="stumbleupon"/> <Icon type="stumbleupon-circled"/> <Icon type="lastfm"/> <Icon type="lastfm-circled"/> <Icon type="rdio"/> <Icon type="rdio-circled"/> <Icon type="spotify"/> <Icon type="spotify-circled"/> <Icon type="qq"/> <Icon type="instagrem"/> <Icon type="dropbox"/> <Icon type="evernote"/> <Icon type="flattr"/> <Icon type="skype"/> <Icon type="skype-circled"/> <Icon type="renren"/> <Icon type="sina-weibo"/> <Icon type="paypal"/> <Icon type="picasa"/> <Icon type="soundcloud"/> <Icon type="mixi"/> <Icon type="behance"/> <Icon type="google-circles"/> <Icon type="vkontakte"/> <Icon type="smashing"/> <Icon type="sweden"/> <Icon type="db-shape"/> <Icon type="logo-db"/> </div> ));
app/app/pages/fetch/component.js
snowkeeper/systemjs-reactjs-hot-reload
import React from 'react'; import Fetch from './fetch'; import Debug from 'debug' let debug = Debug('lodge:app:pages:fetch:component'); export default (page, returnType, options) => { class GenericFetch extends React.Component { constructor(props) { super(props) this.displayName = 'Generic ' + page this.state = { html: props.html || props.response } this.props = props } render() { debug('render fetch component', this.state, page); if('function' === typeof this.state.html) { return (<div> <this.state.html { ...this.props } /> </div>); } else { return (<div dangerouslySetInnerHTML={{ __html: this.state.html }} />) } } } return Fetch(page, GenericFetch, returnType, options) }
node_modules/rc-hammerjs/es/Hammer.js
prodigalyijun/demo-by-antd
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; // https://github.com/hammerjs/hammer.js/issues/930 // https://github.com/JedWatson/react-hammerjs/issues/14 // wait to see if we need the condition require hack for ssr import Hammer from 'hammerjs'; var privateProps = { children: true, direction: true, options: true, recognizeWith: true, vertical: true }; /** * Hammer Component * ================ */ var handlerToEvent = { action: 'tap press', onDoubleTap: 'doubletap', onPan: 'pan', onPanCancel: 'pancancel', onPanEnd: 'panend', onPanStart: 'panstart', onPinch: 'pinch', onPinchCancel: 'pinchcancel', onPinchEnd: 'pinchend', onPinchIn: 'pinchin', onPinchOut: 'pinchout', onPinchStart: 'pinchstart', onPress: 'press', onPressUp: 'pressup', onRotate: 'rotate', onRotateCancel: 'rotatecancel', onRotateEnd: 'rotateend', onRotateMove: 'rotatemove', onRotateStart: 'rotatestart', onSwipe: 'swipe', onSwipeRight: 'swiperight', onSwipeLeft: 'swipeleft', onSwipeUp: 'swipeup', onSwipeDown: 'swipedown', onTap: 'tap' }; Object.keys(handlerToEvent).forEach(function (i) { privateProps[i] = true; }); function updateHammer(hammer, props) { var _this = this; if (props.hasOwnProperty('vertical')) { console.warn('vertical is deprecated, please use `direction` instead'); } var directionProp = props.direction; if (directionProp || props.hasOwnProperty('vertical')) { var direction = directionProp ? directionProp : props.vertical ? 'DIRECTION_ALL' : 'DIRECTION_HORIZONTAL'; hammer.get('pan').set({ direction: Hammer[direction] }); hammer.get('swipe').set({ direction: Hammer[direction] }); } if (props.options) { Object.keys(props.options).forEach(function (option) { if (option === 'recognizers') { Object.keys(props.options.recognizers).forEach(function (gesture) { var recognizer = hammer.get(gesture); recognizer.set(props.options.recognizers[gesture]); if (props.options.recognizers[gesture].requireFailure) { recognizer.requireFailure(props.options.recognizers[gesture].requireFailure); } }, _this); } else { var key = option; var optionObj = {}; optionObj[key] = props.options[option]; hammer.set(optionObj); } }, this); } if (props.recognizeWith) { Object.keys(props.recognizeWith).forEach(function (gesture) { var recognizer = hammer.get(gesture); recognizer.recognizeWith(props.recognizeWith[gesture]); }, this); } Object.keys(props).forEach(function (p) { var e = handlerToEvent[p]; if (e) { hammer.off(e); hammer.on(e, props[p]); } }); } var HammerComponent = function (_React$Component) { _inherits(HammerComponent, _React$Component); function HammerComponent() { _classCallCheck(this, HammerComponent); return _possibleConstructorReturn(this, (HammerComponent.__proto__ || Object.getPrototypeOf(HammerComponent)).apply(this, arguments)); } _createClass(HammerComponent, [{ key: 'componentDidMount', value: function componentDidMount() { this.hammer = new Hammer(ReactDOM.findDOMNode(this)); updateHammer(this.hammer, this.props); } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { if (this.hammer) { updateHammer(this.hammer, this.props); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.hammer) { this.hammer.stop(); this.hammer.destroy(); } this.hammer = null; } }, { key: 'render', value: function render() { var props = {}; Object.keys(this.props).forEach(function (i) { if (!privateProps[i]) { props[i] = this.props[i]; } }, this); // Reuse the child provided // This makes it flexible to use whatever element is wanted (div, ul, etc) return React.cloneElement(React.Children.only(this.props.children), props); } }]); return HammerComponent; }(React.Component); HammerComponent.displayName = 'Hammer'; HammerComponent.propTypes = { className: PropTypes.string }; export default HammerComponent;
node_modules/react-router/modules/RouteUtils.js
Maxwelloff/react-football
import React from 'react' import warning from './routerWarning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) /* istanbul ignore if: error logging */ if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (routes && !Array.isArray(routes)) { routes = [ routes ] } return routes }
src/development/index.js
RedgooseDev/react-photo-layout-editor
import React from 'react'; import ReactDOM from 'react-dom'; import PhotoLayoutEditor from '../PhotoLayoutEditor'; import * as util from './util'; import '../PhotoLayoutEditor/style/app.scss'; import './index.scss'; class App extends React.Component { constructor(props) { super(props); this._photoLayoutEditor = null; } action(id, value) { let result = null; let keys = []; let preference = null; switch(id) { // SIDE case 'side.add': this._photoLayoutEditor.api.side.add(util.pickImages(3)); break; case 'side.selection': result = this._photoLayoutEditor.api.side.selection([0,2,4,6,8,10]); break; case 'side.select': this._photoLayoutEditor.api.side.select({ 0: { active: false }, 1: { active: true }, 2: { active: false }, 3: { active: true } }); break; case 'side.toggleSelectAll': this._photoLayoutEditor.api.side.toggleSelectAll(); break; case 'side.selectedRemoveItems': keys = this._photoLayoutEditor.api.side.getKeys('selected'); this._photoLayoutEditor.api.side.remove(keys); break; case 'side.clear': this._photoLayoutEditor.api.side.clear(); break; case 'side.attachToGrid': keys = this._photoLayoutEditor.api.side.getKeys('selected'); this._photoLayoutEditor.api.side.attachToGrid(keys); break; case 'side.upload': this._photoLayoutEditor.api.side.upload(value.target.files); break; case 'side.getItems': keys = this._photoLayoutEditor.api.side.getKeys('selected'); result = this._photoLayoutEditor.api.side.getItems(keys); console.log('side.getItems', result); break; case 'side.getImages': keys = this._photoLayoutEditor.api.side.getKeys('selected'); result = this._photoLayoutEditor.api.side.getImages(keys); console.log('side.getImages', result); break; // GRID case 'grid.getKeys': //result = this._photoLayoutEditor.api.grid.getKeys('all'); result = this._photoLayoutEditor.api.grid.getKeys('selected'); //result = this._photoLayoutEditor.api.grid.getKeys('value', [0,2,4,6,8]); console.log('get keys:', result); break; case 'grid.getBlocks': //result = this._photoLayoutEditor.api.grid.getBlocks('all'); result = this._photoLayoutEditor.api.grid.getBlocks('selected'); //result = this._photoLayoutEditor.api.grid.getBlocks('value', [0,2,4,6,8]); console.log('get blocks:', result); break; case 'grid.shuffle': this._photoLayoutEditor.api.grid.shuffle({ w: 3, h: 3 }); break; case 'grid.assignImages': this._photoLayoutEditor.api.grid.assignImages(util.pickImages(4)); break; case 'grid.assignImage': this._photoLayoutEditor.api.grid.assignImage(0, util.pickImages(1)[0]); break; case 'grid.update': let result = {}; let blocks = this._photoLayoutEditor.api.grid.getBlocks('selected'); if (!Object.keys(blocks).length) return; Object.keys(blocks).forEach((k) => { blocks[k].color = 'rgba(126,211,33,1)'; }); this._photoLayoutEditor.api.grid.update(blocks); break; case 'grid.add': this._photoLayoutEditor.api.grid.add([{ layout: { w: 1, h: 1 }, color: 'rgba(126,211,33,1)', }]); break; case 'grid.remove': let keys = this._photoLayoutEditor.api.grid.getKeys('selected'); this._photoLayoutEditor.api.grid.remove(keys); //this._photoLayoutEditor.api.grid.remove([0,1]); break; case 'grid.select': this._photoLayoutEditor.api.grid.select([0,2,3]); break; case 'grid.unselect': this._photoLayoutEditor.api.grid.unselect([2,3]); break; case 'grid.toggleSelectAll': this._photoLayoutEditor.api.grid.toggleSelectAll(); break; case 'grid.duplicate': keys = this._photoLayoutEditor.api.grid.getKeys('selected'); this._photoLayoutEditor.api.grid.duplicate(keys); break; case 'grid.getPreference': result = this._photoLayoutEditor.api.grid.getPreference(); console.log('side.getPreference', result); break; case 'grid.setPreference': this._photoLayoutEditor.api.grid.setPreference({ width: 80, column: 6, innerMargin: 5, }); break; // Util case 'util.toggleSide': this._photoLayoutEditor.api.util.toggleSide(); break; case 'util.export.side': result = this._photoLayoutEditor.api.util.export('side'); console.log('export(side)', result); break; case 'util.export.grid': result = this._photoLayoutEditor.api.util.export('grid'); console.log('export(grid)', result); break; case 'util.export.preference': result = this._photoLayoutEditor.api.util.export('preference'); console.log('export(preference)', result); break; case 'util.export.all': result = this._photoLayoutEditor.api.util.export('all'); console.log('export(all)', result); break; case 'util.import.side': result = this._photoLayoutEditor.api.util.import({ side: util.pickImages(3) }, true); break; case 'util.import.grid': this._photoLayoutEditor.api.util.import({ grid: [ { color: '#ee4149', layout: { w: 1, h: 1, x: 0 } }, { color: '#36b40d', layout: { w: 2, h: 2, x: Infinity } }, { color: '#b188ff', layout: { w: 3, h: 1, y: 2, x: 0 } }, ] }, true); break; case 'util.import.preference': preference = this._photoLayoutEditor.api.util.export('preference'); preference = Object.assign({}, preference, { width: 120, height: 80, innerMargin: 2, bgColor: '#ffefc2' }); this._photoLayoutEditor.api.util.import({ preference }); break; case 'util.import.all': preference = this._photoLayoutEditor.api.util.export('preference'); this._photoLayoutEditor.api.util.import({ side: util.pickImages(3), grid: [ { color: '#ee4149', layout: { w: 1, h: 1, x: 0 } }, { color: '#36b40d', layout: { w: 2, h: 2, x: Infinity } }, ], preference: Object.assign({}, preference, { width: 120, height: 80, innerMargin: 2, bgColor: '#ffefc2' }) }); break; case 'util.makeImage': let makeImage = this._photoLayoutEditor.api.util.makeImage('jpg', .9, 2, 'base64'); makeImage.progress(function(total, current, image) { console.log('PROGRESS', total, current, image); }); makeImage.done(function(src) { console.warn('DONE'); let output = document.getElementById('makeImageArea'); output.innerHTML = `<img src="${src}" alt="output image"/>`; }); makeImage.fail(function(error) { console.error('ERROR', error); }); break; } } render() { return ( <div className="app"> <PhotoLayoutEditor ref={(r) => { this._photoLayoutEditor = r }} side={{ files: util.pickImages(5) }} body={{ grid: [ { layout: { x: 0, y: 0, w: 2, h: 2 } }, { layout: { x: 2, y: 0, w: 1, h: 2 } }, { layout: { x: 3, y: 0, w: 2, h: 1 } }, { layout: { x: 3, y: 1, w: 1, h: 1 } }, { layout: { x: 4, y: 1, w: 1, h: 1 } }, ] }} //uploadScript="http://localhost/lab/uploader/upload.php" uploadParamsConvertFunc={(file) => { return file.url; }} updateStoreFunc={() => console.warn('update store')} callback={{ init: () => { console.log('init component') }, sideUploadStart: () => { console.log('side/upload start'); }, sideUploadProgress: (loaded, total, percent) => { console.log('side/upload progress', loaded, total, percent); }, sideUploadComplete: (res) => { console.log('side/upload complete', res); }, sideUploadCompleteAll: () => { console.log('side/upload complete all'); }, sideUploadFail: (error) => { console.log('side/upload fail', error); }, sideRemove: (images) => { console.log('side/remove', images); }, }} /> <article className="api-control"> <section> <h1>Side</h1> <nav> <p> <button type="button" onClick={() => this.action('side.add')}> add files </button> <button type="button" onClick={() => this.action('side.selectedRemoveItems')}> remove items </button> <button type="button" onClick={() => this.action('side.clear')}> clear </button> <button type="button" onClick={() => this.action('side.attachToGrid')}> attach to grid </button> <button type="button" onClick={() => this.action('side.selection')}> selection </button> <button type="button" onClick={() => this.action('side.select')}> select </button> <button type="button" onClick={() => this.action('side.toggleSelectAll')}> toggle select all </button> <button type="button" onClick={() => this.action('side.getItems')}> get items </button> <button type="button" onClick={() => this.action('side.getImages')}> get images </button> </p> <p> <label> <strong>upload image</strong><br/> <input type="file" multiple={true} onChange={(e) => this.action('side.upload', e)}/> </label> </p> </nav> </section> <section> <h1>Grid</h1> <nav> <p> <button type="button" onClick={() => this.action('grid.getKeys')}>get keys</button> <button type="button" onClick={() => this.action('grid.getBlocks')}>get blocks</button> <button type="button" onClick={() => this.action('grid.getPreference')}>get preference</button> <button type="button" onClick={() => this.action('grid.setPreference')}>set preference</button> <button type="button" onClick={() => this.action('grid.update')}>update</button> <button type="button" onClick={() => this.action('grid.add')}>add</button> <button type="button" onClick={() => this.action('grid.remove')}>remove</button> <button type="button" onClick={() => this.action('grid.shuffle')}>shuffle</button> <button type="button" onClick={() => this.action('grid.assignImages')}>assign images</button> <button type="button" onClick={() => this.action('grid.assignImage')}>assign image</button> <button type="button" onClick={() => this.action('grid.duplicate')}>duplicate</button> <button type="button" onClick={() => this.action('grid.select')}>select</button> <button type="button" onClick={() => this.action('grid.unselect')}>unselect</button> <button type="button" onClick={() => this.action('grid.toggleSelectAll')}>toggle select all</button> </p> </nav> </section> <section> <h1>Util</h1> <nav> <p> <button type="button" onClick={() => this.action('util.toggleSide')}>Toggle side</button> </p> <p> <button type="button" onClick={() => this.action('util.export.side')}>Export(side)</button> <button type="button" onClick={() => this.action('util.export.grid')}>Export(grid)</button> <button type="button" onClick={() => this.action('util.export.preference')}>Export(preference)</button> <button type="button" onClick={() => this.action('util.export.all')}>Export(all)</button> <button type="button" onClick={() => this.action('util.makeImage')}>Make image</button> </p> <p> <button type="button" onClick={() => this.action('util.import.side')}>Import(side)</button> <button type="button" onClick={() => this.action('util.import.grid')}>Import(grid)</button> <button type="button" onClick={() => this.action('util.import.preference')}>Import(preference)</button> <button type="button" onClick={() => this.action('util.import.all')}>Import(all)</button> </p> </nav> </section> <section> <h1>Make image area</h1> <figure id="makeImageArea"/> </section> </article> </div> ); } } ReactDOM.render(<App/>, document.getElementById('app'));
src/views/syllabus/Aspect.js
bostontrader/senmaker
// @flow import React from 'react' import LessonNavigator from './LessonNavigator' import {VerbdPanelLevel} from '../../data/dictionary/verbd/VerbdConstants' function Aspect(props:Object):Object { const style:Object = { border: '1px solid black', margin: '5px' } const q:Object = props.quiz const s:Object = props.strings.aspect /*const quizInsertVerbFlag = q.getIn(['verbd','insertAspect']) ? <img id="insertAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : '' const quizUpdateVerbFlag = q.getIn(['verbd','updateAspect']) ? <img id="updateAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : '' const quizDeleteVerbFlag = q.getIn(['verbd','deleteAspect']) ? <img id="deleteAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : ''*/ return( <div> <div className="help" style={style}> <h1>Aspect</h1> {s.map(h => (<p>{h}</p>))} </div> <div className="quiz" style={style}> <h3>{props.strings.quiz}</h3> <table> <tbody> </tbody> </table> </div> <LessonNavigator {...props} /> </div> ) } export default Aspect
react/life-cycle/src/LifeCycle.js
kobeCan/practices
import React from 'react'; class LifeCycle extends React.Component { constructor (props) { super(props); } state = { color: 'red' } /* 当组件第一次挂载的时候 */ // 1. componentWillMount = () => { console.log('componentWillMount'); } // 2. 在render之后执行 componentDidMount = () => { console.log('componentDidMount'); } /* 当接收到父组件的props或state发生改变的时候 */ // 1. componentWillReceiveProps = (nextProps, nextState) => { console.log('componentWillReceiveProps'); } // 2. shouldComponentUpdate = (nextProps, nextState) => { console.log('shouldComponentUpdate'); return true; } // 3. componentWillUpdate = (nextProps, nextState) => { console.log('componentWillUpdate'); } // 4. 在render之后执行 componentDidUpdate = () => { console.log('componentDidUpdate'); } handleClick = () => { this.setState({ color: '#' + Math.round(Math.random() * 0xffffff).toString(16) }) } render () { const { text } = this.props; const { color } = this.state; return <div> <h2 onClick={this.handleClick} style={{color: color}}>{text}</h2> </div>; } } export default LifeCycle
src/components/ChartBase.js
somonus/react-echarts
import React, { Component } from 'react'; export default class ChartBase extends Component { static propTypes = { hasChart: React.PropTypes.bool, }; constructor(props) { super(props); if (this.props.hasChart !== true) { throw new Error('There is no Chart wrapper.'); } } render() { return null; } }
egghead-redux/redux-app/src/components/app2.js
Mad-Labs/open-lab
import React, { Component } from 'react'; import Debug from './debug'; import {runTestSuite} from '../reducers/multipleCountersReducer'; class App2 extends Component { render() { return ( <div> <h1>Test add/remove counters</h1> <Debug result={runTestSuite()} /> </div> ); } } export default App2;
node_modules/react-sparklines/src/SparklinesCurve.js
aleksandrsmolin/react-redux-weather
import React from 'react'; export default class SparklinesCurve extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style, divisor = 0.25 } = this.props; let prev; const curve = (p) => { let res; if (!prev) { res = [p.x, p.y] } else { const len = (p.x - prev.x) * divisor; res = [ "C", //x1 prev.x + len, //y1 prev.y, //x2, p.x - len, //y2, p.y, //x, p.x, //y p.y ]; } prev = p; return res; } const linePoints = points .map((p) => curve(p)) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ "L" + points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: style.fill || color || 'slategray' }; return ( <g> <path d={"M"+fillPoints.join(' ')} style={fillStyle} /> <path d={"M"+linePoints.join(' ')} style={lineStyle} /> </g> ) } }
src/svg-icons/hardware/sim-card.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSimCard = (props) => ( <SvgIcon {...props}> <path d="M19.99 4c0-1.1-.89-2-1.99-2h-8L4 8v12c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM9 19H7v-2h2v2zm8 0h-2v-2h2v2zm-8-4H7v-4h2v4zm4 4h-2v-4h2v4zm0-6h-2v-2h2v2zm4 2h-2v-4h2v4z"/> </SvgIcon> ); HardwareSimCard = pure(HardwareSimCard); HardwareSimCard.displayName = 'HardwareSimCard'; HardwareSimCard.muiName = 'SvgIcon'; export default HardwareSimCard;
webui/components/users/FormInsurance.js
stiftungswo/izivi_relaunch
import React from 'react'; import { Grid } from 'semantic-ui-react'; import AutoField from 'uniforms-semantic/AutoField'; import SubmitField from 'uniforms-semantic/SubmitField'; import ErrorsField from 'uniforms-semantic/ErrorsField'; import AutoForm from 'uniforms-semantic/AutoForm'; import FormMaskedInput from '../../lib/FormMaskedInput'; const FormInsurance = formProps => ( <AutoForm showInlineError {...formProps} > <Grid stackable columns={3}> <Grid.Row> <Grid.Column computer={4} tablet={5}> <AutoField name="healthInsuranceNumber" placeholder="00000" /> </Grid.Column> <Grid.Column computer={8} tablet={11}> <AutoField name="healthInsuranceName" /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column computer={4} tablet={5}> <AutoField name="socialSecurityNumber" component={FormMaskedInput} mask="756.9999.9999.99" maskChar="_" alwaysShowMask /> </Grid.Column> </Grid.Row> <Grid.Row columns={1}> <Grid.Column> <ErrorsField /> <SubmitField value="Speichern" className="primary" /> </Grid.Column> </Grid.Row> </Grid> </AutoForm> ); export default FormInsurance;
pootle/static/js/admin/components/Search.js
translate/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import cx from 'classnames'; import React from 'react'; import ItemTable from './ItemTable'; import SearchBox from './SearchBox'; const Search = React.createClass({ propTypes: { fields: React.PropTypes.array.isRequired, onSearch: React.PropTypes.func.isRequired, onSelectItem: React.PropTypes.func.isRequired, items: React.PropTypes.object.isRequired, selectedItem: React.PropTypes.object, searchLabel: React.PropTypes.string.isRequired, searchPlaceholder: React.PropTypes.string.isRequired, resultsCaption: React.PropTypes.string.isRequired, searchQuery: React.PropTypes.string.isRequired, }, /* Lifecycle */ getInitialState() { return { isLoading: false, }; }, /* State-changing callbacks */ onResultsFetched() { this.setState({ isLoading: false }); }, fetchResults(query) { this.setState({ isLoading: true }); this.props.onSearch(query).then(this.onResultsFetched); }, loadMore() { this.fetchResults(this.props.searchQuery); }, /* Layout */ render() { const { isLoading } = this.state; const { items } = this.props; let loadMoreBtn; if (items.count > 0 && items.length < items.count) { loadMoreBtn = ( <button className="btn" onClick={this.loadMore} > {gettext('Load More')} </button> ); } const resultsClassNames = cx({ 'search-results': true, loading: isLoading, }); return ( <div className="search"> <div className="hd"> <h2>{this.props.searchLabel}</h2> </div> <div className="bd"> <div className="search-box"> <SearchBox onSearch={this.props.onSearch} placeholder={this.props.searchPlaceholder} searchQuery={this.props.searchQuery} /> </div> <div className={resultsClassNames}> {isLoading && this.props.items.length === 0 ? <div>{gettext('Loading...')}</div> : <div> <ItemTable fields={this.props.fields} items={items} resultsCaption={this.props.resultsCaption} selectedItem={this.props.selectedItem} onSelectItem={this.props.onSelectItem} /> {loadMoreBtn} </div> } </div> </div> </div> ); }, }); export default Search;
geonode/contrib/monitoring/frontend/src/components/cels/geonode-data/index.js
simod/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getResponseData } from '../../../utils'; import AverageResponseTime from '../../molecules/average-response-time'; import MaxResponseTime from '../../molecules/max-response-time'; import TotalRequests from '../../molecules/total-requests'; import styles from './styles'; import actions from './actions'; const mapStateToProps = (state) => ({ interval: state.interval.interval, response: state.geonodeAverageResponse.response, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class GeonodeData extends React.Component { static propTypes = { get: PropTypes.func.isRequired, interval: PropTypes.number, reset: PropTypes.func.isRequired, response: PropTypes.object, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.get = (interval = this.props.interval) => { this.props.get(interval); }; } componentWillMount() { this.get(); } componentWillReceiveProps(nextProps) { if (nextProps) { if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) { this.get(nextProps.interval); } } } componentWillUnmount() { this.props.reset(); } render() { let averageResponseTime = 0; let maxResponseTime = 0; let totalRequests = 0; [ averageResponseTime, maxResponseTime, totalRequests, ] = getResponseData(this.props.response); return ( <div style={styles.content}> <h5>Geonode Data Overview</h5> <div style={styles.geonode}> <AverageResponseTime time={averageResponseTime} /> <MaxResponseTime time={maxResponseTime} /> </div> <TotalRequests requests={totalRequests} /> </div> ); } } export default GeonodeData;
admin/client/components/ItemsTable/ItemsTable.js
Tangcuyu/keystone
import React from 'react'; import classnames from 'classnames'; import Columns from '../../columns'; import CurrentListStore from '../../stores/CurrentListStore'; import ListControl from '../List/ListControl'; import TableRow from './ItemsTableRow'; import DrapDrop from './ItemsTableDragDrop'; const TABLE_CONTROL_COLUMN_WIDTH = 26; // icon + padding const ItemsTable = React.createClass({ propTypes: { columns: React.PropTypes.array, items: React.PropTypes.object, list: React.PropTypes.object, }, renderCols () { var cols = this.props.columns.map((col) => <col width={col.width} key={col.path} />); // add delete col when applicable if (!this.props.list.nodelete) { cols.unshift(<col width={TABLE_CONTROL_COLUMN_WIDTH} key="delete" />); } // add sort col when applicable if (this.props.list.sortable) { cols.unshift(<col width={TABLE_CONTROL_COLUMN_WIDTH} key="sortable" />); } return <colgroup>{cols}</colgroup>; }, renderHeaders () { let listControls = 0; if (this.props.list.sortable) listControls++; if (!this.props.list.nodelete) listControls++; // span first col for controls when present let cellPadding = null; if (listControls) { cellPadding = <th colSpan={listControls}></th>; } let cells = this.props.columns.map((col, i) => { return <th key={col.path} colSpan="1">{col.label}</th>; }); return <thead><tr>{cellPadding}{cells}</tr></thead>; }, render () { const { items, list } = this.props; if (!items.results.length) return null; const currentPage = CurrentListStore.getCurrentPage(); const pageSize = CurrentListStore.getPageSize(); const totalPages = Math.ceil(items.count / pageSize); const tableBody = (this.props.list.sortable) ? ( <DrapDrop { ...this.props } /> ) : ( <tbody > {items.results.map((item, i) => { return ( <TableRow key={item.id} deleteTableItem={this.props.deleteTableItem} index={i} sortOrder={item.sortOrder || 0} id={item.id} item={item} { ...this.props } /> ); })} </tbody> ); return ( <div className="ItemList-wrapper"> <table cellPadding="0" cellSpacing="0" className="Table ItemList"> {this.renderCols()} {this.renderHeaders()} {tableBody} </table> </div> ); }, }); module.exports = exports = ItemsTable;
dataTool/stories/examples/index.js
bitmoremedia/mygi
import React from 'react' import { storiesOf } from '@kadira/storybook' import globalStyles from '../../src/global-styles'; globalStyles(); import ButtonToggle from './ButtonToggle' import ButtonToggleModal from './ButtonToggleModal' import SearchUtility from './SearchUtility' storiesOf('Toggle Display', module) .add('ButtonToggle', () => ( <ButtonToggle /> )) .add('ButtonToggleModal', () => ( <ButtonToggleModal /> )) storiesOf('Utilities', module) .add('SearchUtility', () => ( <SearchUtility /> ))
front/app/app/rh-components/rh-Spinner.js
nudoru/React-Starter-2-app
import React from 'react'; const Spinner = ({type}) => { let cls = ['spinner']; if(type) { cls.push(type); } return (<div className={cls.join(' ')}></div>) }; export default Spinner;
src/pages/404.js
jgaehring/jgaehring.github.io
import React from 'react'; import Layout from '../components/Layout'; const NotFoundPage = () => ( <Layout> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) export default NotFoundPage
app/javascript/mastodon/features/explore/links.js
musashino205/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Story from './components/story'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import { connect } from 'react-redux'; import { fetchTrendingLinks } from 'mastodon/actions/trends'; const mapStateToProps = state => ({ links: state.getIn(['trends', 'links', 'items']), isLoading: state.getIn(['trends', 'links', 'isLoading']), }); export default @connect(mapStateToProps) class Links extends React.PureComponent { static propTypes = { links: ImmutablePropTypes.list, isLoading: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; componentDidMount () { const { dispatch } = this.props; dispatch(fetchTrendingLinks()); } render () { const { isLoading, links } = this.props; return ( <div className='explore__links'> {isLoading ? (<LoadingIndicator />) : links.map(link => ( <Story key={link.get('id')} url={link.get('url')} title={link.get('title')} publisher={link.get('provider_name')} sharedTimes={link.getIn(['history', 0, 'accounts']) * 1 + link.getIn(['history', 1, 'accounts']) * 1} thumbnail={link.get('image')} blurhash={link.get('blurhash')} /> ))} </div> ); } }
src/components/amount-input.js
mozilla/donate.mozilla.org
import React from 'react'; var AmountInput = React.createClass({ contextTypes: { intl: React.PropTypes.object }, getInitialState: function() { var amount = this.props.amount; if (amount) { amount = this.context.intl.formatNumber(amount); } return { inputValue: amount }; }, componentWillReceiveProps: function(nextProps) { var amount = nextProps.amount; var inputValue = this.state.inputValue; if (!amount && inputValue) { this.setState({ inputValue: "" }); } else if (amount && !inputValue) { this.setState({ inputValue: this.context.intl.formatNumber(amount) }); } }, onInputChange: function(e) { var inputValue = e.currentTarget.value; var amount = ""; // TODO: This needs to be refactored to use regex replace // and needs documentation for what they are matching. // See https://github.com/mozilla/donate.mozilla.org/issues/1917 if (/^[\d]*[.]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/,/g, ""); } else if (/^[\d]*[,]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/\./g, "").replace(",", "."); } else if (/^[\d,]*[.]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/,/g, ""); } else if (/^[\d.]*[,]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/\./g, "").replace(",", "."); } else { inputValue = this.state.inputValue; } if (this.state.inputValue !== inputValue) { this.setState({ inputValue: inputValue }); this.props.onInputChange(amount); } }, onClick: function(e) { if (this.props.onInputClick) { this.props.onInputClick(e); } }, render: function() { var inputValue = this.state.inputValue; if (!this.props.amount) { inputValue = ""; } var id = this.props.id || ""; var className = this.props.className || ""; var placeholder = this.props.placeholder || ""; var type = this.props.type || ""; return ( <input id={id} autoComplete="off" className={className} type={type} value={inputValue} onClick={this.onClick} placeholder={placeholder} onChange={this.onInputChange} /> ); } }); module.exports = AmountInput;
src/svg-icons/maps/terrain.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsTerrain = (props) => ( <SvgIcon {...props}> <path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/> </SvgIcon> ); MapsTerrain = pure(MapsTerrain); MapsTerrain.displayName = 'MapsTerrain'; MapsTerrain.muiName = 'SvgIcon'; export default MapsTerrain;
src/containers/app.js
mrGGoodbye/react-redux-API-unsplash
// подключаем необходимые модули React и Unsplash import React from 'react'; import { connect } from 'react-redux' import { action_SET_list_photos } from '../actions'; import {unsplash} from '../../src/index.js'; import {Router, Route, hashHistory, Link} from 'react-router'; // счетчик страниц и количества фоток на каждой странице let page = 1; const n = 10; // функция загруки первого списка фотографий const func_list_photo=(func_new_list_photo)=>{ console.log('unsplash in app.js==',unsplash); // делаем запрос в unsplash unsplash.photos.listPhotos(page, n, "latest") .then(res => res.json()) .then(json => { console.log('JSON_list_photo__TOKEN--- ', json); let propValue=[]; // разбираем полученный результат и сохраняем его в propValue for(let prop in json){ if(json.hasOwnProperty(prop)){ // let propValue = json[prop].urls.small; propValue = [ ...propValue, { id: json[prop].id, url: json[prop].urls.small, url_full: json[prop].urls.full, author_name: json[prop].user.name, author_link: json[prop].user.links.html, date: json[prop].created_at, likes: json[prop].likes, liked_by_user: json[prop].liked_by_user } ]; console.log(prop+' : ', propValue); } } console.log('MASSSIVE_PHOTO : ', propValue); // для каждого элемента propValue вызываем функцию, // которая вызовет action-creators "action_SET_list_photos" propValue.map((item, i)=>{ func_new_list_photo(propValue[i]); }) }); } // эта функция будет загружать новые списки фото // будем листать страницы const func_load_foto=(func_new_list_photo, load_ok)=>{ console.log('Загружаем еще фото...'); // листаем следующую станицу page = page + 1; // делаем запрос в UNSPLASH unsplash.photos.listPhotos(page, n, "latest") .then(res => res.json()) .then(json => { // Your code console.log('NEW_JSON_list_photo__TOKEN--- ', json); let propValue=[]; // разбираем полученный результат и сохраняем его в propValue for(let prop in json){ if(json.hasOwnProperty(prop)){ propValue = [ ...propValue, { id: json[prop].id, url: json[prop].urls.small, url_full: json[prop].urls.full, author_name: json[prop].user.name, author_link: json[prop].user.links.html, date: json[prop].created_at, likes: json[prop].likes, liked_by_user: json[prop].liked_by_user } ]; console.log(prop+' : ', propValue); } } console.log('NEW_MASSSIVE_NEW_PHOTO : ', propValue); // для каждого элемента propValue вызываем функцию, // которая вызовет action-creators "action_SET_list_photos" propValue.map((item, i)=>{ func_new_list_photo(propValue[i]); }) load_ok = true; }); // end my code } // делаем счетчик рендинга при первоначальной загрузке странице // чтобы не загружать несколько раз пока незагружен первый результат, // так как ему нужно время для получения результата и загрузки let nn=0; let load_first = true; let func_log = () => { console.log("Сработало! ---- ", nn++); load_first = false; } // Создаем компонен App_Con // основной компонент будет показывать список фотографий let App_Con = (props) =>{ console.log('PROPS_QWERTY==', props); // загружаем первый списко через Timeout // иначе из unsplash загрузятся не актульные данные по лайкам польлзователя const for_timeout=()=>{ func_list_photo(props.func_new_list_photo); console.log('Timeout Ok'); } if(nn==1){ setTimeout(for_timeout, 1000); } func_log(); // load_ok - для подстраховки если пока незагрузились новые фото // будут крутить скролом на месте удовлетворяющем условиям let load_ok = true; // функция для отлавливания момента скрола вниз для загрузки новых фото window.onscroll = function() { var app2 = document.querySelector('#app2'); if((load_ok)&&(window.scrollY>=app2.clientHeight - window.innerHeight+26)&&(window.location.hash=='#/')) { console.log('END!!! ',window.scrollY); load_ok = false; func_load_foto(props.func_new_list_photo, load_ok); } } // сторим наше приложение // загружаем первый список фото // новый список загружаем при скроле в самый низ или по нажатии кнопки return ( <div > <h2> Мой Unsplash </h2> <div> {props.IMGGESS.map((el,i) =>{ var date = new Date(el.date); return <div key={i} > <div><Link to={`/photo/${el.id}`} key={i+100}><img src={el.url} /></Link></div> <div><a href={el.author_link+'?utm_source=over&utm_medium=referral&utm_campaign=api-credit'} target="_blank" key={i+10}>{el.author_name}</a></div> <div>Дата публикации: {date.toUTCString()}</div> <div>Количество лайков: {el.likes}</div> </div> })} </div> <button className={'button_load_foto'} onClick={ev=>func_load_foto(props.func_new_list_photo)} >Загрузить еще...</button> </div> ) } // создаем store и action-creators const mapStateToProps = (state, ownProps) => { return { todos: state.todos, IMGGESS: state.IMGGESS, ownProps } } const mapDispatchToProps = (dispatch) => { return { // функция для listPhotos func_new_list_photo: (props) => { dispatch(action_SET_list_photos(props)) } } } let App_Con22 = connect( mapStateToProps, mapDispatchToProps )(App_Con) export default App_Con22;
src/pages/components/Books/utils.js
H3yfinn/finbarmaunsell.com
// @flow import React from 'react' import type { _Book } from './types' // Note that this is different from `renderWiki` in the Elm, // as we cannot return an Html.Attribute msg (attribute assignment) // as a single value in JS in the same way that we can in Elm. export const deduceUrl = (book: _Book) => book.wiki || '' export const renderErr = (error: ?string) => ( (typeof error === 'string') ? <div>{error}</div> : null ) export const isComplete = (book: _Book) => (typeof book.end === 'string') // this synthesises the check in Elm, but important // to mention null values in JS and their nuances
app/javascript/mastodon/components/animated_number.js
tri-star/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
examples/todomvc/containers/Root.js
ariporad/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
WorldMoodTracker/js/components/Header.js
kavithaenair/kavithaenair.github.io
import React from 'react'; import styles from '../../../css/bootstrap.min.css'; import customStyles from '../../css/style.css'; export default class Header extends React.Component { render() { return ( <nav className={[styles.navbar].join(' ')}> <div className={styles.container}> <div className={styles.navbarHeader} style={{marginLeft: '10px'}}> <h1> <span>World Mood Tracker</span> </h1> <h3> Powered by&nbsp; <span className={customStyles.loklak}> <a href="http://loklak.org" target="_blank">loklak</a> </span> </h3> </div> <div className={[styles.collapse, styles.navbarCollapse].join(' ')}> <ul className={[styles.nav, styles.navbarNav, styles.navbarRight].join(' ')}> <li><a href="/">Home</a></li> <li><a href="#">About</a></li> <li><a href="https://github.com/fossasia/apps.loklak.org/tree/master/WorldMoodTracker" target="_blank">Github</a></li> </ul> </div> </div> </nav> ) } }
src/js/components/dailyTracker/UnitTimer.js
angelm/sinuous
import React from 'react'; class UnitTimer extends React.Component { constructor(props) { super(props); let time = new Date(); time.setMinutes(props.unitDuration || 25); time.setSeconds(0); this.state = { timeoutId: null, remainingTime: time }; this.startTimer = this.startTimer.bind(this); this.pauseTimer = this.pauseTimer.bind(this); this.resetTimer = this.resetTimer.bind(this); } startTimer() { this.setState({timeoutId: setTimeout(this.onInterval.bind(this), this.state.interval)}); } pauseTimer() { if(this.state && this.state.timeoutId){ clearTimeout(this.state.timeoutId); } } resetTimer() { if(this.state && this.state.timeoutId){ clearTimeout(this.state.timeoutId); } let time = new Date(); time.setMinutes(this.props.unitDuration || 25); time.setSeconds(0); this.setState({remainingTime: time}); } onInterval(){ var mins = this.state.remainingTime.getMinutes(); var secs = this.state.remainingTime.getSeconds(); let remainingTime = new Date(this.state.remainingTime.getTime()); remainingTime.setSeconds(remainingTime.getSeconds() - 1); this.setState({remainingTime: remainingTime}); if(mins == 0 && secs == 0){ this.onCountdownEnded() } else { clearTimeout(this.state.timeoutId); this.setState({timeoutId: setTimeout(this.onInterval.bind(this), 1000)}); } } onCountdownEnded() { // Todo: notify of unit complete to the TaskManager and DailySummary console.log("Unit Completed"); } formatClock(){ let mins = this.state.remainingTime.getMinutes(); let secs = this.state.remainingTime.getSeconds(); let strMins = mins < 10 ? "0" + mins : mins; let strSecs = secs < 10 ? "0" + secs : secs; return strMins + ':' + strSecs; } render() { return ( <div className="timer"> <div className="clock">{this.formatClock()}</div> <div className="control-panel"> <div className="control time start fa fa-play-circle" onClick={this.startTimer}></div> <div className="control stop fa fa-pause-circle" onClick={this.pauseTimer}></div> <div className="control reset fa fa-stop-circle" onClick={this.resetTimer}></div> </div> </div> ); } } export default UnitTimer;
client/App.js
Trulsabe/reactLinuxMern
/** * Root Component */ import React from 'react'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import IntlWrapper from './modules/Intl/IntlWrapper'; // Import Routes import routes from './routes'; // Base stylesheet require('./main.css'); export default function App(props) { return ( <Provider store={props.store}> <IntlWrapper> <Router history={browserHistory}> {routes} </Router> </IntlWrapper> </Provider> ); } App.propTypes = { store: React.PropTypes.object.isRequired, };
src/LabelNumberDisplay/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Icon from '../Icon'; import Typography from '../Typography'; import classNames from 'classnames'; import styles from './styles.css'; function LabelNumberDisplay(props) { return ( <div className={classNames(styles.outerWrapper, props.className)}> <Icon className={styles.icon} icon={props.icon || 'icon-leaf'} size={'standard'} style={{color: props.color ? props.color : '#00ab97'}} /> <Typography className={classNames(styles.value, {[styles.valueDark]: props.theme === 'dark'})} type={'display1'} > {props.value} </Typography> <Typography className={classNames(styles.label, {[styles.labelDark]: props.theme === 'dark'})} type={'bodyTextNormal'} >{props.label}</Typography> </div> ); } LabelNumberDisplay.propTypes = { className: PropTypes.string, color: PropTypes.string, icon: PropTypes.string, label: PropTypes.string, theme: PropTypes.string, value: PropTypes.number }; export default LabelNumberDisplay;
Backup/AwesomeProject/components/TaskList.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, TextInput, Text, Button, AlertIOS } from 'react-native'; import HeaderIQMail from './Faixa'; import { Container, Content, InputGroup, Input } from 'native-base'; export default class TaskList extends Component{ constructor(){ super(); this.state = { todoTxt: '', todos: [] } } render(){ return( <View> <HeaderIQMail></HeaderIQMail> <View> <InputGroup borderType='regular' > <Input onChangeText={ this.handleChange } value={ this.state.todoTxt } placeholder='Digite sua Lista'/> </InputGroup> <Button title='New Todo' onPress={this.save}> </Button> </View> <View> { this.state.todos.map((item, key) => ( <Text key = {key}>{item}</Text> ))} </View> </View> ); } handleChange = (txt) => { this.setState({ todoTxt:txt }) } save = () => { if(!this.state.todoTxt) { AlertIOS.alert('Por favor, preencha o campo.'); } this.state.todos.push(this.state.todoTxt); this.setState({ todoTxt: '', todos : this.state.todos }); } }
src/components/header/ThemeSwitcher.js
TechyFatih/Nuzlog
import React from 'react'; import { ToggleButton, ToggleButtonGroup } from 'react-bootstrap' const stylesheet = document.getElementById('bootstrap'); export default class ThemeSwitcher extends React.Component { constructor(props) { super(props); this.state = {value: 'default'}; this.onChange = this.onChange.bind(this); } onChange(value) { this.setState({ value }); const link = 'bootstrap/css/bootstrap' + (value == 'dark' ? '-dark' : '') + '.min.css'; stylesheet.setAttribute('href', link); } render() { return ( <ToggleButtonGroup type='radio' name='theme' value={this.state.value} onChange={this.onChange}> <ToggleButton value='default'>Default</ToggleButton> <ToggleButton value='dark'>Dark</ToggleButton> </ToggleButtonGroup> ) } }
part4/src/components/Button/index.js
vulcan-estudios/web-testing
import React from 'react'; function Button (props = {}) { const { className, icon } = props; let { children } = props; let cls = 'mybutton'; if (className) { cls += ` ${className}`; } if (icon) { children = ( <i className='myicon' /> ); } return ( <button className={cls}> {children} </button> ); } export default Button;
src/svg-icons/action/schedule.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSchedule = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); ActionSchedule = pure(ActionSchedule); ActionSchedule.displayName = 'ActionSchedule'; ActionSchedule.muiName = 'SvgIcon'; export default ActionSchedule;
pkg/interface/groups/src/js/components/lib/group-sidebar.js
ngzax/urbit
import React, { Component } from 'react'; import { Route, Link } from 'react-router-dom'; import { GroupItem } from '/components/lib/group-item'; import { Sigil } from '/components/lib/icons/sigil'; import { SidebarInvite } from '/components/lib/sidebar-invite'; import { Welcome } from '/components/lib/welcome'; import { cite } from '/lib/util'; export class GroupSidebar extends Component { // drawer to the left render() { const { props, state } = this; let selectedClass = (props.selected === "me") ? "bg-gray4 bg-gray1-d" : "bg-white bg-gray0-d"; let rootIdentity = <Link key={1} to={"/~groups/me"}> <div className={ "w-100 pl4 pt1 pb1 f9 flex justify-start content-center " + selectedClass}> <Sigil ship={window.ship} color="#000000" classes="mix-blend-diff" size={32}/> <p className="f9 w-70 dib v-mid ml2 nowrap mono" style={{paddingTop: 6}}> {cite(window.ship)} </p> </div> </Link> let inviteItems = Object.keys(props.invites) .map((uid) => { let invite = props.invites[uid]; return ( <SidebarInvite key={uid} api={api} invite={invite} uid={uid} history={props.history} /> ); }); let groupItems = Object.keys(props.contacts) .filter((path) => { return ( (!path.startsWith("/~/")) && (path in props.groups) ); }) .filter((path) => { let selectedGroups = !!props.selectedGroups ? props.selectedGroups : []; if (selectedGroups.length === 0) { return true; } let selectedPaths = selectedGroups.map((e => {return e[0]})); return (selectedPaths.includes(path)); }) .sort((a, b) => { let aName = a.substr(1); let bName = b.substr(1); let aChannel = `${a}/contacts${a}` let bChannel = `${b}/contacts${b}` if ( props.associations[a] && props.associations[a][aChannel] && props.associations[a][aChannel].metadata ) { aName = props.associations[a][aChannel].metadata.title !== "" ? props.associations[a][aChannel].metadata.title : a.substr(1); } if ( props.associations[b] && props.associations[b][bChannel] && props.associations[b][bChannel].metadata ) { bName = props.associations[b][bChannel].metadata.title !== "" ? props.associations[b][bChannel].metadata.title : b.substr(1); } return aName.toLowerCase().localeCompare(bName.toLowerCase()); }) .map((path) => { let name = path.substr(1); let selected = props.selected === path; let groupChannel = `${path}/contacts${path}` if ( props.associations[path] && props.associations[path][groupChannel] && props.associations[path][groupChannel].metadata ) { name = props.associations[path][groupChannel].metadata.title !== "" ? props.associations[path][groupChannel].metadata.title : path.substr(1); } return ( <GroupItem key={path} link={path} selected={selected} name={name} group={props.groups[path]} contacts={props.contacts[path]} /> ) }); let activeClasses = (this.props.activeDrawer === "groups") ? "" : "dn-s"; return ( <div className={"bn br-m br-l br-xl b--gray4 b--gray1-d lh-copy h-100 " + "flex-basis-30-ns flex-shrink-0 mw5-m mw5-l mw5-xl flex-basis-100-s " + "relative overflow-hidden pt3 pt0-m pt0-l pt0-xl " + activeClasses}> <a className="db dn-m dn-l dn-xl f8 pb6 pl3" href="/">⟵ Landscape</a> <div className="overflow-auto pb8 h-100"> <Link to="/~groups/new" className="dib"> <p className="f9 pt4 pl4 green2 bn">Create Group</p> </Link> <Welcome contacts={props.contacts}/> <h2 className="f9 pt4 pr4 pb2 pl4 gray2 c-default">Your Identity</h2> {rootIdentity} {inviteItems} <h2 className="f9 pt4 pr4 pb2 pl4 gray2 c-default">Groups</h2> {groupItems} </div> </div> ); } }
src/svg-icons/navigation/fullscreen-exit.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationFullscreenExit = (props) => ( <SvgIcon {...props}> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/> </SvgIcon> ); NavigationFullscreenExit = pure(NavigationFullscreenExit); NavigationFullscreenExit.displayName = 'NavigationFullscreenExit'; NavigationFullscreenExit.muiName = 'SvgIcon'; export default NavigationFullscreenExit;
src/components/Main.js
diaotai/gallery
require('normalize.css/normalize.css'); require('styles/App.scss'); var imageDatas=require("../data/imageDatas.json") import React from 'react'; // let yeomanImage = require('../images/1.jpg'); //将图片名信息转化为图片URL信息 function genURLImageData(datas){ for(let i=0;i<datas.length;i++) { let singleImageData=datas[i]; singleImageData.imageURL=require('../images/'+singleImageData.fileName) datas[i]=singleImageData } return datas; } imageDatas=genURLImageData(imageDatas) //获取区间内的随机值 function getRangeRandom(low,high){ return Math.ceil(Math.random()*(high-low)+low); } //用于获取0~30度之间的任意一个正负值 function get30DegRandom(){ return (Math.random()>0.5?'':'-')+Math.ceil(Math.random()*30) } class ImgFigure extends React.Component{ constructor(props){ super(props) this.handleClick=this.handleClick.bind(this) } handleClick(e){ if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.stopPropagation(); e.preventDefault(); } render(){ let styleObj = {}; //如果props属性中制定了这张图片的位置,则使用 if(this.props.arrange.pos){ styleObj=this.props.arrange.pos; } //如过图片的旋转角度有值且不为0,则使用 否则添加旋转角度 if(this.props.arrange.rotate){ (['MozTransfrom','msTransfrom','WebkitTransfrom','transform']).forEach(function(value){ styleObj[value]='rotate('+this.props.arrange.rotate+'deg)'; },this); } if(this.props.arrange.isCenter){ styleObj.zIndex=11; } //本处可能有错 let imgFigureClassName='img-figure'; imgFigureClassName+=this.props.arrange.isInverse?' is-inverse':''; return( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p>{this.props.data.desc}</p> </div> </figcaption> </figure> ) } } class ControllerUnit extends React.Component{ constructor(props){ super(props) this.handleClick=this.handleClick.bind(this) } handleClick(e){ //如果点击选中态按钮,则反转,否则居中 if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.preventDefault(); e.stopPropagation(); } render(){ let controllerUnitClassName="controller-unit"; //如果对应剧中图片,显示居中态 if(this.props.arrange.isCenter){ controllerUnitClassName+=" is-center"; //如果同时还是翻转态 if(this.props.arrange.isInverse) controllerUnitClassName+=" is-inverse"; } return( <span className={controllerUnitClassName} onClick={this.handleClick} ></span> ); } } // var ControllerUnit = React.createClass({ // handleClick: function(e){ // //如果点击的是当前选中态的按钮,则翻转图片,否则将对应的图片居中 // if(this.props.arrange.isCenter){ // this.props.inverse(); // } else{ // this.props.center(); // } // e.preventDefault(); // e.stopPropagation(); // }, // render: function(){ // var controllerUnitClassName = 'controller-unit'; // //如果对应的是居中的图片,显示控制按钮的居中态 // if(this.props.arrange.isCenter){ // controllerUnitClassName += ' is-center'; // //如果同时对应的是反转图片,显示控制按钮的翻转态 // if(this.props.arrange.isInverse){ // controllerUnitClassName += ' is-inverse'; // } // } // return( // <span className={controllerUnitClassName} onClick={this.handleClick}></span> // ); // } // }) class AppComponent extends React.Component { constructor(props){ super(props) this.state={ imgsArrangeArr:[ { pos:{ left:'0', right:'0' }, rotate:0,//旋转角度 isInverse:false, //图片正反,默认为正面, isCenter:false } ] } this.Constant={ centerPos:{ left:0, right:0 }, hPosRange:{ leftSecX:[0,0], rightSecX:[0,0], y:[0,0] }, vPosRange:{ x:[0,0], topY:[0,0] } } this.rearrane=this.rearrane.bind(this); this.center=this.center.bind(this); this.inverse=this.inverse.bind(this); } center(index){ return function(){ this.rearrane(index); }.bind(this); } inverse(index){ //console.log(this); return function(){ // console.log(this.state); let imgsArrangeArr=this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse=!imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr:imgsArrangeArr }) }.bind(this); } /* *重新布局所有图片 *param centerIndex指定哪一个图片居中 */ rearrane(centerIndex){ let imgsArrangeArr=this.state.imgsArrangeArr; let Constant=this.Constant, centerPos=Constant.centerPos, hPosRange=Constant.hPosRange, vPosRange=Constant.vPosRange, hPosRangeLeftSecX=hPosRange.leftSecX, hPosRangeRightSecX=hPosRange.rightSecX, hPosRangeY=hPosRange.y, vPosRangeTopY=vPosRange.topY, vPosRangeX=vPosRange.x, imgsArrangeTopArr=[], topImgNum=Math.floor(Math.random()*2) //取一个或者不取 let topImgSpliceIndex=0, imgsArrangeCenterArr=imgsArrangeArr.splice(centerIndex,1); //首先居中centerIndex的图片 imgsArrangeCenterArr[0]={ pos:centerPos, rotate:0, isCenter:true } //去除布局上侧图片的状态信息 topImgSpliceIndex=Math.ceil(Math.random()*(imgsArrangeArr,length-topImgNum)); imgsArrangeTopArr=imgsArrangeArr.splice(topImgSpliceIndex,topImgNum); //布局位于上侧的图片 imgsArrangeTopArr.forEach(function(value,index){ imgsArrangeTopArr[index]={ pos:{ top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]), left:getRangeRandom(vPosRangeX[0],vPosRangeX[1]) }, rotate:get30DegRandom(), isCenter:false } }); for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; // 前半部分布局左边, 右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate:get30DegRandom(), isCenter:false }; } //布局左右两侧的图片 // for(let i=0;i<imgsArrangeArr.length;i++){ // let hPosRangeLORX=null; // if(i<imgsArrangeArr/2){ // hPosRangeLORX= hPosRangeLeftSecX; // }else{ // hPosRangeLORX=hPosRangeRightSecX; // } // imgsArrangeArr[i].pos={ // top:getRangeRandom(hPosRangeY[0],hPosRangeY[1]), // left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1]) // } // } if(imgsArrangeTopArr&&imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]); //console.log(imgsArrangeCenterArr[0].pos.left,imgsArrangeCenterArr[0].pos.top) this.setState({ imgsArrangeArr:imgsArrangeArr }); } componentDidMount(){ //获取舞台的大小 var stageDOM = this.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW=Math.ceil(stageW/2), halfStageH=Math.ceil(stageH/2); //拿到一个imageFigure的大小 let imgFigureDOM=this.refs.imgFigure0, imgW=320, imgH=360, halfImgW=Math.ceil(imgW / 2), halfImgH=Math.ceil(imgH / 2); /* console.log(imgFigureDOM) console.log('stage'+stageW+' '+stageH) console.log('img'+imgW+' '+imgH) */ this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH } // console.log('center'+this.Constant.centerPos.left) //计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[0] = stageH - halfImgH; //计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfImgW; // this.rearrange(0); // //计算中心图片的位置点 // this.Constant.centerPos={ // left:halfStageW - halfImgW, // top:halfStageH - halfImgH // } // //左侧及右侧区域的位置数据 // this.Constant.hPosRange.leftSecX[0]=-halfImgW; // this.Constant.hPosRange.leftSecX[1]=halfStageW - 3 * halfImgW; // this.Constant.hPosRange.rightSecX[0]=halfStageW + halfImgW; // this.Constant.hPosRange.rightSecX[1]=stageW - halfImgW; // this.Constant.hPosRange.y[0]=-halfImgH; // this.Constant.hPosRange.y[1]=stageH - halfImgH; // //上侧区域位置数据 // this.Constant.vPosRange.topY[0]=-halfImgH; // this.Constant.vPosRange.topY[1]=halfStageH - halfImgH * 3; // this.Constant.vPosRange.x[0]=halfStageW - imgW; // this.Constant.vPosRange.x[1]=halfStageW; this.rearrane(0); } render() { let controlers=[],imgFigures=[]; imageDatas.forEach(function(value,index){ if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index]={ pos:{ left:0, top:0 }, rotate:0, isInverse:false, isCenter:false } } imgFigures.push(<ImgFigure data={value} key={index} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>); controlers.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>) },this); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controlers} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/index.js
alexras/truepeacein.space
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import DocumentTitle from 'react-document-title'; import './index.css'; ReactDOM.render( ( <DocumentTitle title='truepeacein.space | Metroid Password Generator'> <App /> </DocumentTitle> ), document.getElementById('root'));
examples/huge-apps/routes/Calendar/components/Calendar.js
moudy/react-router
import React from 'react'; class Calendar extends React.Component { render () { var events = [{ id: 0, title: 'essay due' }]; return ( <div> <h2>Calendar</h2> <ul> {events.map(event => ( <li key={event.id}>{event.title}</li> ))} </ul> </div> ); } } export default Calendar;
src/components/Select/Select-story.js
jzhang300/carbon-components-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import Select from '../Select'; import SelectItem from '../SelectItem'; import SelectItemGroup from '../SelectItemGroup'; const selectProps = { onChange: action('onChange'), className: 'some-class', }; storiesOf('Select', module) .addWithInfo( 'enabled', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create Select Item components for each option in the list. The example below shows an enabled Select component with three items. `, () => ( <Select {...selectProps} id="select-1" defaultValue="placeholder-item"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Category 1"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> <SelectItem value="option-4" text="Option 4" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'inline', ` Inline select is for use when there will be multiple elements in a row `, () => ( <Select {...selectProps} inline id="select-1" defaultValue="placeholder-item"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Starter"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Advanced"> <SelectItem value="option-3" text="Option 3" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'disabled', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create SelectItem components for each option in the list. The example below shows an disabled Select component. `, () => ( <Select disabled {...selectProps} id="select-2"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Category 1"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'no label', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create SelectItem components for each option in the list. The example below shows a Select component without a label. `, () => ( <Select {...selectProps} id="select-3" defaultValue="placeholder-item" hideLabel> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Starter"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> <SelectItem value="option-4" text="Option 4" /> </SelectItemGroup> </Select> ) );
app/javascript/mastodon/features/community_timeline/components/column_settings.js
sylph-sin-tyaku/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} /> </div> </div> ); } }
client/src/components/UploadField/UploadFieldItem.js
open-sausages/silverstripe-asset-admin
import i18n from 'i18n'; import React, { Component } from 'react'; import CONSTANTS from 'constants'; import fileShape from 'lib/fileShape'; import { fileSize } from 'lib/DataFormat'; import PropTypes from 'prop-types'; class UploadFieldItem extends Component { constructor(props) { super(props); this.handleRemove = this.handleRemove.bind(this); this.handleItemClick = this.handleItemClick.bind(this); this.handleView = this.handleView.bind(this); } /** * Gets props for thumbnail * * @returns {Object} */ getThumbnailStyles() { if (this.isImage() && (this.exists() || this.uploading())) { const thumbnail = this.props.item.smallThumbnail || this.props.item.url; return { backgroundImage: `url(${thumbnail})`, }; } return {}; } /** * Retrieve list of thumbnail classes * * @returns {string} */ getThumbnailClassNames() { const thumbnailClassNames = ['uploadfield-item__thumbnail']; if (this.isImageSmallerThanThumbnail()) { thumbnailClassNames.push('uploadfield-item__thumbnail--small'); } return thumbnailClassNames.join(' '); } /** * Retrieves class names for the item * * @returns {string} */ getItemClassNames() { const category = this.props.item.category || 'none'; const itemClassNames = [ 'fill-width', 'uploadfield-item', `uploadfield-item--${category}`, ]; if (this.missing()) { itemClassNames.push('uploadfield-item--missing'); } if (this.hasError()) { itemClassNames.push('uploadfield-item--error'); } return itemClassNames.join(' '); } /** * Checks if the component has an error set. * * @return {boolean} */ hasError() { if (this.props.item.message) { return this.props.item.message.type === 'error'; } return false; } /** * Determine if this is an image type * * @returns {Boolean} */ isImage() { return this.props.item.category === 'image'; } /** * Validate that the file backing this record is not missing * * @returns {Boolean} */ exists() { return this.props.item.exists; } /** * Check if this item is in the process uploaded. * If false this file was attached to this editor instead. * * @returns {boolean} */ uploading() { return this.props.item.queuedId && !this.saved(); } /** * Check if this item has been successfully uploaded. * Excludes items not uploaded in this request. * * @returns {Boolean} */ complete() { // Uploading is complete if saved with a DB id return this.props.item.queuedId && this.saved(); } /** * Check if this item has been saved, either in this request or in a prior one * * @return {Boolean} */ saved() { return this.props.item.id > 0; } /** * Check if this item should have a file, but is missing. * * @return {Boolean} */ missing() { return !this.exists() && this.saved(); } /** * Determine that this record is an image, and the thumbnail is smaller than the given * thumbnail area * * @returns {boolean} */ isImageSmallerThanThumbnail() { if (!this.isImage() || this.missing()) { return false; } const width = this.props.item.width; const height = this.props.item.height; // Note: dimensions will be null if the back-end image is lost return ( height && width && height < CONSTANTS.SMALL_THUMBNAIL_HEIGHT && width < CONSTANTS.SMALL_THUMBNAIL_WIDTH ); } /** * Handles remove (x) button click * * @param {Object} event */ handleRemove(event) { event.preventDefault(); if (this.props.onRemove) { this.props.onRemove(event, this.props.item); } } /** * Handles edit button click * * @param {Object} event */ handleView(event) { event.preventDefault(); if (this.props.onView) { this.props.onView(event, this.props.item); } } /** * Handles click of an item * * @param {Object} event */ handleItemClick(event) { event.preventDefault(); if (this.props.onItemClick) { this.props.onItemClick(event, this.props.item); } } renderStatus() { if (this.props.item.draft) { return ( <span className="uploadfield-item__status">{i18n._t('File.DRAFT', 'Draft')}</span> ); } else if (this.props.item.modified) { return ( <span className="uploadfield-item__status">{i18n._t('File.MODIFIED', 'Modified')}</span> ); } return null; } /** * Returns markup for an error message if one is set. * * @returns {Object} */ renderErrorMessage() { let message = null; if (this.hasError()) { message = this.props.item.message.value; } else if (this.missing()) { message = i18n._t('AssetAdmin.FILE_MISSING', 'File cannot be found'); } if (message !== null) { return ( <div className="uploadfield-item__error-message" title={message}> {message} </div> ); } return null; } /** * Gets upload progress bar * * @returns {object} */ renderProgressBar() { const progressBarProps = { className: 'uploadfield-item__progress-bar', style: { width: `${this.props.item.progress}%`, }, }; if (!this.hasError() && this.props.item.queuedId) { if (this.complete()) { return ( <div className="uploadfield-item__complete-icon" /> ); } return ( <div className="uploadfield-item__upload-progress"> <div {...progressBarProps} /> </div> ); } return null; } /** * Gets the remove item button * * @returns {object} */ renderRemoveButton() { if (!this.props.canEdit) { return null; } const classes = [ 'btn', 'uploadfield-item__remove-btn', 'btn-secondary', 'btn--no-text', 'font-icon-cancel', 'btn--icon-md', ].join(' '); return ( <button className={classes} onClick={this.handleRemove} /> ); } /** * Gets the edit item button * * @returns {object} */ renderViewButton() { if (!this.props.canEdit || !this.props.item.id) { return null; } const classes = [ 'btn', 'uploadfield-item__view-btn', 'btn-secondary', 'btn--no-text', 'font-icon-eye', 'btn--icon-md', ].join(' '); return ( <button className={classes} onClick={this.handleView} /> ); } /** * Get file title / metadata block * * @returns {object} */ renderFileDetails() { let size = ''; if (this.props.item.size) { size = `, ${fileSize(this.props.item.size)}`; } return ( <div className="uploadfield-item__details fill-height flexbox-area-grow"> <div className="fill-width"> <span className="uploadfield-item__title flexbox-area-grow"> {this.props.item.title} </span> </div> <div className="fill-width uploadfield-item__meta"> <span className="uploadfield-item__specs"> {this.props.item.extension}{size} </span> {this.renderStatus()} </div> </div> ); } renderThumbnail() { return ( <div className={this.getThumbnailClassNames()} style={this.getThumbnailStyles()} onClick={this.handleItemClick} role="button" tabIndex={this.props.onItemClick ? 0 : -1} /> ); } /** * * @returns {object} */ render() { const fieldName = `${this.props.name}[Files][]`; return ( <div className={this.getItemClassNames()}> <input type="hidden" value={this.props.item.id} name={fieldName} /> {this.renderThumbnail()} {this.renderFileDetails()} {this.renderProgressBar()} {this.renderErrorMessage()} {this.renderViewButton()} {this.renderRemoveButton()} </div> ); } } UploadFieldItem.propTypes = { canEdit: PropTypes.bool, name: PropTypes.string.isRequired, item: fileShape, onRemove: PropTypes.func, onItemClick: PropTypes.func, onView: PropTypes.func, }; export default UploadFieldItem;
frontend/src/Settings/DownloadClients/DownloadClients/DownloadClients.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Card from 'Components/Card'; import FieldSet from 'Components/FieldSet'; import Icon from 'Components/Icon'; import PageSectionContent from 'Components/Page/PageSectionContent'; import { icons } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import AddDownloadClientModal from './AddDownloadClientModal'; import DownloadClient from './DownloadClient'; import EditDownloadClientModalConnector from './EditDownloadClientModalConnector'; import styles from './DownloadClients.css'; class DownloadClients extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isAddDownloadClientModalOpen: false, isEditDownloadClientModalOpen: false }; } // // Listeners onAddDownloadClientPress = () => { this.setState({ isAddDownloadClientModalOpen: true }); }; onAddDownloadClientModalClose = ({ downloadClientSelected = false } = {}) => { this.setState({ isAddDownloadClientModalOpen: false, isEditDownloadClientModalOpen: downloadClientSelected }); }; onEditDownloadClientModalClose = () => { this.setState({ isEditDownloadClientModalOpen: false }); }; // // Render render() { const { items, onConfirmDeleteDownloadClient, ...otherProps } = this.props; const { isAddDownloadClientModalOpen, isEditDownloadClientModalOpen } = this.state; return ( <FieldSet legend={translate('DownloadClients')}> <PageSectionContent errorMessage={translate('UnableToLoadDownloadClients')} {...otherProps} > <div className={styles.downloadClients}> { items.map((item) => { return ( <DownloadClient key={item.id} {...item} onConfirmDeleteDownloadClient={onConfirmDeleteDownloadClient} /> ); }) } <Card className={styles.addDownloadClient} onPress={this.onAddDownloadClientPress} > <div className={styles.center}> <Icon name={icons.ADD} size={45} /> </div> </Card> </div> <AddDownloadClientModal isOpen={isAddDownloadClientModalOpen} onModalClose={this.onAddDownloadClientModalClose} /> <EditDownloadClientModalConnector isOpen={isEditDownloadClientModalOpen} onModalClose={this.onEditDownloadClientModalClose} /> </PageSectionContent> </FieldSet> ); } } DownloadClients.propTypes = { isFetching: PropTypes.bool.isRequired, error: PropTypes.object, items: PropTypes.arrayOf(PropTypes.object).isRequired, onConfirmDeleteDownloadClient: PropTypes.func.isRequired }; export default DownloadClients;
src/routes.js
tylerchilds/pokedex
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './pages/app'; import Type from './pages/type'; import PokemonList from './pages/pokemon-list'; import Pokemon from './pages/pokemon'; const routes = ( <Route path="/" component={ App }> <IndexRoute component={ PokemonList } /> <Route path="type/:type" component={ Type } /> <Route path="pokemon/:pokemon" component={ Pokemon } /> </Route> ); export default routes;
javascript/ShareAdmin/AuthKeyForm.js
AppStateESS/stories
'use strict' import React from 'react' import PropTypes from 'prop-types' import InputField from '@essappstate/canopy-react-inputfield' const AuthKeyForm = ({host, update, save}) => { if (!host) { return <div></div> } return (<div> <InputField value={host.authkey} change={update} placeholder="Paste in authkey received from host."/> <button className="btn btn-primary" onClick={save}>Save</button> </div>) } AuthKeyForm.propTypes = { host: PropTypes.object, update: PropTypes.func, save: PropTypes.func, } export default AuthKeyForm
node_modules/semantic-ui-react/src/elements/List/ListContent.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, SUI, useValueAndKey, useVerticalAlignProp, } from '../../lib' import ListDescription from './ListDescription' import ListHeader from './ListHeader' /** * A list item can contain a content. */ function ListContent(props) { const { children, className, content, description, floated, header, verticalAlign, } = props const classes = cx( useValueAndKey(floated, 'floated'), useVerticalAlignProp(verticalAlign), 'content', className, ) const rest = getUnhandledProps(ListContent, props) const ElementType = getElementType(ListContent, props) if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType> return ( <ElementType {...rest} className={classes}> {ListHeader.create(header)} {ListDescription.create(description)} {content} </ElementType> ) } ListContent._meta = { name: 'ListContent', parent: 'List', type: META.TYPES.ELEMENT, } ListContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Shorthand for ListDescription. */ description: customPropTypes.itemShorthand, /** An list content can be floated left or right. */ floated: PropTypes.oneOf(SUI.FLOATS), /** Shorthand for ListHeader. */ header: customPropTypes.itemShorthand, /** An element inside a list can be vertically aligned. */ verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS), } ListContent.create = createShorthandFactory(ListContent, content => ({ content })) export default ListContent
docs/src/components/Playground/Playground.js
seekinternational/seek-asia-style-guide
import styles from './Playground.less'; import React, { Component } from 'react'; import { Alert, TextField, Button, ButtonGroup, StarIcon, MailIcon, PageBlock, Section, AsidedLayout, Columns, Card, CardGroup, Text, Positive, Critical, Secondary, Strong, Footer } from 'seek-asia-style-guide/react'; import JobStreetHeader from 'seek-asia-style-guide/jobStreet/Header/Header'; import TextLink from './Atoms/TextLink/TextLink'; import IconButton from './Atoms/IconButton/IconButton'; import Tab from './Atoms/Tab/Tab'; const renderAsideProfile = () => ( <Card transparent> <Section> <Text shouting>Profile visibility</Text> <Text secondary>Employers cant view your profile or resumes or contact you with job opportunities.</Text> </Section> </Card> ); const renderAsideProfilePhoto = () => ( <div> <Text screaming>Tom Cliff</Text> <Text waving> <div>0412 345 678</div> <div>Add a home location</div> <div>[email protected]</div> </Text> </div> ); const renderAsideSignIn = () => ( <Card transparent> <Section className={styles.marketing}> <Text shouting>Make the most of SEEK</Text> <Text>Only employers registered with SEEK can see your profile</Text> <Text>Save time everytime with pre-filled application forms</Text> <Text>Be the first to receive latest jobs and industry insights</Text> </Section> </Card> ); const renderAsideRegister = renderAsideSignIn; const renderAsideRecommendedJobs = () => ( <Card> <Section> <Text shouting>How it works</Text> <Text>Every day we look for new opportunities for you based on your profile, search, save and apply activity.</Text> <Text><TextLink href="https://www.seek.com.au">Review your profile</TextLink></Text> <Text><TextLink href="https://www.seek.com.au">Start a new search</TextLink></Text> </Section> </Card> ); const renderAsideMyActivity = () => ( <div className={styles.activityPanel}> <Text>Applied on SEEK 20 Dec 2016</Text> <div className={styles.activityMobileCustom}> <div className={styles.touchable}> No Cover Letter </div> <TextLink href="https://www.seek.com.au">Download Resume</TextLink> </div> </div> ); const renderAsideMyActivityActions = () => ( <div> <IconButton icon="delete">Remove Job</IconButton> </div> ); const renderJobDetailDate = () => ( <Text yelling secondary>18 Jan 2017</Text> ); const renderJobDetailMetadata = () => ( <div> <Card> <Section> <Button color="pink" className={styles.fullWidthTextField}>Apply for this job</Button> <Text secondary> <br /> {'Applications for this role will take you to the advertiser\'s site.'} <br /> <br /> </Text> <Columns tight> <Button color="gray" className={styles.fullWidthTextField}><StarIcon /> Save Job</Button> <Button color="gray" className={styles.fullWidthTextField}><MailIcon /> Send Job</Button> </Columns> </Section> </Card> <Card> <Section> <Text strong raw>Melbourne,</Text> <Text>CBD & Inner Suburbs</Text> <Text strong>Base + Super</Text> <Text strong>Full time</Text> <Text strong raw>Information & Communication Technology</Text> <Text>Architects</Text> </Section> </Card> </div> ); const jobDetailsContent = '<HTML><p><strong>About SEEK</strong></p> <p>We are&nbsp;the global leader in the creation and operation of online employment markets. In the ASX Top 50, SEEK has enjoyed being one of Australia\'s fastest growing businesses with a consistent and formidable position of market leadership across Australia and New Zealand and ownership stakes in leading companies across China, Brazil, Mexico, Africa and SE Asia.&nbsp;</p> <p><strong>Multiple Opportunities&nbsp;</strong></p> <p>We&nbsp;have three Software Architect opportunities currently&nbsp;available&nbsp;at SEEK. All three roles are similar from a role and day to day&nbsp;perspective, however they have&nbsp;different development and technology strategy focus&nbsp;areas, being:&nbsp;Core Business, Mobile and Cloud.</p> <p><strong>About the Opportunities&nbsp;</strong></p> <p>The Software Architect is a technology leadership position at SEEK: you\'ll drive large transformational change across IT on behalf of the business. These opportunities will enable you to:&nbsp;</p> <ul><li>Work in a passionate,&nbsp;fast growing environment where the ability to learn and adapt quickly to new methodologies and technologies is valued.</li><li>Collaborate with&nbsp;cross-functional, multi-disciplinary teams to deliver excellent software for our customers in an agile environment.</li><li>Be part of a fun, successful global online business with a diverse team of development, operations and security minded folks.</li><li>Act as an enabler for the team, removing obstacles and identifying process and technological improvements.</li><li>Strive for technical excellence and help facilitate the healthy tension between the delivery and the long term viability of the code base</li><li>Actively participate and contribute to communities of practice at SEEK and beyond.</li></ul> <p><strong>Your Work</strong></p> <p>Your work will be a compelling mix of working embedded within delivery teams and of broader architectural responsibilities, which will include:</p> <ul><li>Getting your hands dirty delivering working software</li><li>Paving the way for development streams to adopt new technology, software patterns and approaches</li><li>Providing guidance to delivery</li><li>Developing solutions, tools and processes and technological roadmaps</li><li>Leading external vendor and emergent technology evaluation</li><li>Running and supporting the technical communities of practice</li></ul> <p><strong>To Succeed&nbsp;</strong></p> <p>To be successful as a Software Architect at SEEK&nbsp;you will ideally have experiences in:</p> <ul><li>The design, build, operations and evolution of high traffic applications, networks and business critical systems on AWS or native mobile applications&nbsp;OR the modernisation of software systems while delivering on aggressive revenue focussed roadmaps&nbsp;</li><li>Ability to effectively communicate trade-offs and impacts to stakeholders&nbsp;</li><li>In-depth technical knowledge of enterprise, solution and application architectures.</li><li>Practice Evolutionary Design, posses a deep understanding of Solution Design, and be proficient in Domain Driven Design, Design Patterns and Data Modelling, OO principles etc.</li><li>Highly competent in multiple languages across multiple layers of the technology stack.</li><li>Ability to mentor and coach developers and testers to author testable, effective and clean code</li><li>Demonstrated ability to lead and coach others in agile methodologies and development practices such as: CI TDD, BDD, Kanban and Lean.</li></ul> <p><strong>Culture and Benefits</strong></p> <p>SEEK\'s commitment to fostering a productive work environment has helped us drive growth and maintain a consistently high ranking in the annual Hewitt Best Employer Award. The work environment is Agile and fast-paced, with a strong emphasis on outcomes. People like to come here – and we\'re proud of that! And we don\'t have a dress code.</p> <p><strong>How to Apply</strong></p> <p>Click the &quot;Apply for this job&quot; link&nbsp;to begin your application. If you want to know more about the role please do not hesitate to contact<strong> Melanie Whitehouse</strong>, Talent Acquisition Consultant on <strong>(03) 8517 4571</strong>,<strong>&nbsp;</strong>for a confidential conversation.</p> <p><strong>Privacy Policy</strong></p> <p>All personal information received by us from you or about you will be stored, used and disclosed by us in accordance with our privacy policy, a copy of which can be found at www.seek.com.au/privacy. &nbsp;If you&nbsp;have any questions in relation to how we may use and store your personal information please contact us at [email protected].</p></HTML> <HTML>Multiple opportunities available specialising in cloud, mobile and core business Pursue mastery of software delivery and inspire software craftsmanship in others Join a bunch of like minded, smart people doing great things</HTML>'; const footerProps = { country: 'hk', language: 'en' }; export default class Playground extends Component { render() { return ( <div> <Alert hideIcon tone="info" level="primary" onClose={() => {}}><Text>Welcome to our new search page. <span className={styles.alertBreaker}>Find your dream job faster.</span></Text></Alert> <JobStreetHeader language="en" country="my" user={{}} /> <PageBlock> <Section header> <Text screaming>Button Groups</Text> </Section> <AsidedLayout reverse size="340px"> <Card> <Section> <ButtonGroup> <Button color="pink">Sign In</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Create a Profile</Button> <Button color="transparent">Cancel</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="grey">Save job</Button> <Button color="grey">Send job</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Save</Button> <Button color="transparent">Clear</Button> <Button color="transparent">Cancel</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Save</Button> <Button color="grey">Clear</Button> <Button color="grey">Cancel</Button> </ButtonGroup> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock className={styles.header}> <AsidedLayout size="340px"> <Section> <AsidedLayout renderAside={renderAsideProfilePhoto} size="400px"> <Text screaming className={styles.photo}>TC</Text> </AsidedLayout> </Section> </AsidedLayout> </PageBlock> <PageBlock> <AsidedLayout reverse renderAside={renderAsideProfile} size="340px"> <Card> <Section> <Text shouting>Personal summary</Text> <Text>Add a personal summary to your profile as a way to introduce who you are.</Text> <IconButton icon="plus">Add summary</IconButton> </Section> </Card> <Card> <Section> <Text shouting>Career history</Text> <Text>The more you let employers know about your experince the more you can stand out from other candidates.</Text> <IconButton icon="plus">Add Role</IconButton> </Section> </Card> <Card> <Section> <Text shouting>Resumé</Text> <Text waving>Default Resumé</Text> <Text secondary><TextLink href="https://www.seek.com.au">20140714_-_cc11017_development...orm.pdf</TextLink> (75.82KB Added - 16 Dec 2016)</Text> <Text>Your “Default” resumé is not visible to employers.</Text> <Text>Update your privacy setting to “Standard” so that employers can view your resumé and get in contact with job opportunities. <TextLink href="https://www.seek.com.au">Learn more</TextLink> about your privacy.</Text> <Text waving>Other Resumés</Text> <Text secondary><TextLink href="https://www.seek.com.au">Ohter_Resume.pdf</TextLink> (75.82KB Added - 16 Dec 2016)</Text> <IconButton icon="plus">Add summary</IconButton> </Section> </Card> <Card> <Section> <Text shouting>About the role you are looking for</Text> <Text secondary>Classification/s of interest:</Text> <Text secondary>Role type</Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Candidate Sign in</Text> </Section> <AsidedLayout reverse renderAside={renderAsideSignIn} size="360px"> <Card> <Section className={styles.cardHeader}> <TextLink href="https://www.seek.com.au" chevron="right">Are you an Employer?</TextLink> </Section> <Section> <TextField value="" id="email" label="Email address" inputProps={{ type: 'email' }} className={styles.fullWidthTextField} /> <TextField value="" id="password" label="Password" inputProps={{ type: 'password' }} className={styles.fullWidthTextField} /> <div> <TextLink href="https://www.seek.com.au">Forgot your password?</TextLink> </div> <Button color="pink">Sign In</Button> <Text>Don’t have an account? <TextLink href="https://www.seek.com.au">Register</TextLink></Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Register</Text> </Section> <AsidedLayout reverse renderAside={renderAsideRegister} size="360px"> <Card> <Section className={styles.cardHeader}> <TextLink href="https://www.seek.com.au" chevron="right">Are you an Employer?</TextLink> </Section> <Section> <Columns> <TextField value="" id="fname" label="First name" inputProps={{ type: 'text' }} className={styles.fullWidthTextField} /> <TextField value="" id="lname" label="Last name" inputProps={{ type: 'text' }} className={styles.fullWidthTextField} /> </Columns> <TextField value="" id="email" label="Email address" inputProps={{ type: 'email' }} className={styles.fullWidthTextField} /> <TextField value="" id="password" label="Password" inputProps={{ type: 'password' }} className={styles.fullWidthTextField} /> <Text secondary>By registering you agree to the <TextLink href="https://www.seek.com.au">SEEK privacy policy</TextLink></Text> <Button color="pink">Register</Button> <Text>Already have an account? <TextLink href="https://www.seek.com.au">Sign in</TextLink></Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Recommended jobs</Text> <Text>24 jobs showing</Text> <Tab>All</Tab> <Tab selected>New</Tab> </Section> <AsidedLayout reverse renderAside={renderAsideRecommendedJobs} size="240px"> <CardGroup> { [0, 1, 2, 3].map(n => ( <Card key={n}> <Section> <TextLink subheading href="https://www.seek.com.au">Building Supervisor</TextLink> <Text>A1 Building Group</Text> <Text>CBD & Inner Suburbs, Melbourne</Text> </Section> </Card> )) } </CardGroup> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Activity</Text> <Tab selected>Saved</Tab> <Tab>Applied</Tab> </Section> <CardGroup> { [0, 1, 2, 3].map(n => ( <Card key={n}> <Section> <AsidedLayout renderAside={renderAsideMyActivity} size="270px"> <TextLink subheading href="https://www.seek.com.au">Local Health District Registered Nurse</TextLink> <Text>Western NSW Local Health District</Text> <Text raw>Job posted 30d+ ago</Text> <Text raw secondary>Dubbo & Central NSW</Text> <Text secondary>Salary Rate: $29.32 to $41.18 ph</Text> <Text> Are you a Registered Nurse and looking for variety and challenges on a daily basis? Yes? Here is your chance - Full Time or Part-time available. </Text> </AsidedLayout> <AsidedLayout renderAside={renderAsideMyActivityActions} size="270px"> <IconButton icon="plus">Add Notes</IconButton> </AsidedLayout> </Section> </Card> )) } </CardGroup> </PageBlock> <PageBlock> <Section> <TextLink>Back to search results</TextLink> <AsidedLayout renderAside={renderJobDetailDate}> <Text yelling>Software Architect</Text> </AsidedLayout> <TextLink>More jobs from SEEK Limited</TextLink> </Section> <AsidedLayout reverse renderAside={renderJobDetailMetadata} size="360px"> <CardGroup> <Card> <Section> <Text> <div dangerouslySetInnerHTML={{ __html: jobDetailsContent }} // eslint-disable-line react/no-danger /> </Text> </Section> </Card> <Card> <Section> <Text>You must have the <Strong>right to live and work</Strong> in this location to apply for this job.</Text> </Section> </Card> </CardGroup> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>This job is no longer advertised</Text> </Section> <Card> <Section> <Text> Expired jobs remain on SEEK for 90 days after last advertised, or until they are removed by the advertiser. <br /> <br /> </Text> <Button color="pink">Search for another job</Button> </Section> </Card> </PageBlock> <PageBlock> <Section header> <Text screaming>Two columns</Text> </Section> <Columns> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> </Columns> </PageBlock> <PageBlock> <Section header> <Text screaming>Three columns</Text> </Section> <Columns> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> </Columns> </PageBlock> <PageBlock> <Section header> <Text screaming>Text variants</Text> </Section> <CardGroup> <Card> <Section> <Text shouting>Text component modifiers</Text> <Text positive>Positive text</Text> <Text critical>Critical text</Text> <Text secondary>Secondary text</Text> <Text strong>Strong text</Text> </Section> </Card> <Card> <Section> <Text shouting>Inline variant components</Text> <Text><Positive>Positive text</Positive></Text> <Text><Critical>Critical text</Critical></Text> <Text><Secondary>Secondary text</Secondary></Text> <Text><Strong>Strong text</Strong></Text> </Section> </Card> </CardGroup> </PageBlock> <Footer {...footerProps} /> <br /> <Footer {...{ ...footerProps, country: 'sg' }} /> </div> ); } }
pages/index.js
turntwogg/final-round
import React from 'react'; import { Row, Col, useTheme } from '@turntwo/react-ui'; import LazyLoad from 'react-lazyload'; import { FaAngleDoubleRight } from 'react-icons/fa'; import Page from '../components/Page'; import PageContent from '../components/PageContent'; import Container from '../components/Container'; import Heading from '../components/Heading'; import HomePageScreenshot from '../components/HomePageScreenshot'; import CornerBox from '../components/CornerBox'; import Button from '../components/Button'; import ButtonGroup from '../components/ButtonGroup'; import Slice from '../components/Slice'; import GameGrid from '../components/GameGrid'; import Redirect from '../components/Redirect'; import Typography from '../components/Typography'; import useUser from '../hooks/useUser'; import useGames from '../hooks/useGames'; const introSliceColStyles = { margin: 0, backgroundPosition: 'center center', backgroundSize: 'cover', }; const Index = () => { const user = useUser(); const games = useGames(); const theme = useTheme(); const pageHero = ( <div className="page-hero"> <Container> <div className="page-hero__inner"> <div className="page-hero__content"> <div className="page-hero__content-inner"> <div className="line-decoration"> <Typography is="h3" variant="caps" className="tk-rift" style={{ display: 'inline-block', margin: 0, backgroundColor: '#fafafc', position: 'relative', zIndex: 10, paddingRight: 14, color: 'rgba(28, 19, 52, .6)', fontWeight: 400, }} > Stay Connected </Typography> </div> <Typography is="h2" variant="caps" style={{ lineHeight: 1.03, marginBottom: 24, }} className="page-hero-title tk-rift" > Your Favorite <br /> Esports Teams <br /> and Players. </Typography> <ButtonGroup spacing={16}> <Button variant={['fancy', 'dull']} size="xlarge" href="/sign-up" > Sign Up </Button> <Button variant="fancy" size="xlarge" href="/welcome"> Try It Today{' '} <FaAngleDoubleRight style={{ marginLeft: 12 }} size={16} /> </Button> </ButtonGroup> </div> </div> <div className="page-hero__media"> <HomePageScreenshot /> </div> </div> </Container> <style jsx>{` .page-hero__inner { display: flex; flex-flow: column wrap; align-items: center; padding: ${theme.su(1.5)} ${theme.su()}; } .page-hero__content { margin-bottom: ${theme.su(2)}; } .page-hero__media { position: relative; display: flex; width: 100%; flex-basis: 100%; } :global(.page-hero-title) { font-size: 36px; } .line-decoration { position: relative; margin-bottom: 16px; } .line-decoration::after { position: absolute; top: 50%; left: 0; right: 16px; height: 1px; background-color: rgba(28, 19, 52, 0.25); transform: translateY(-50%); content: ''; } @media (min-width: ${theme.breakpoints.m}px) { .page-hero { background-image: url(${require('../static/images/home-screenshot-bg.png')}); background-size: contain; background-repeat: no-repeat; background-position: top right; } .page-hero__inner { flex-flow: row nowrap; justify-content: center; padding: ${theme.su()}; } .page-hero__content { display: flex; flex: 0 0 50%; width: 50%; } .page-hero__content-inner { margin-left: auto; } .page-hero__media { flex: 0 0 50%; max-width: 50%; width: 50%; position: relative; display: flex; flex-direction: column; justify-content: center; height: auto; height: calc(100vh - 90px - 15%); padding-left: 80px; } } @media (min-width: ${theme.breakpoints.mTweak}px) { .page-hero__inner { height: calc(100vh - ${theme.headerHeight.desktop}px); padding: 7.5% 0; } :global(.page-hero-title) { font-size: 60px; } } @media (min-width: ${theme.breakpoints.l}px) { .page-hero__content { display: flex; flex: 0 0 33.33%; width: 33.33%; } .page-hero__media { flex: 0 0 66.66%; max-width: 66.66%; width: 66.66%; } } `}</style> </div> ); if (user && user.uid) { return <Redirect to="/dashboard" />; } return ( <Page style={{ padding: 0 }}> {pageHero} <PageContent fullWidth> <Slice name="intro" noPadding> <Row style={{ margin: 0 }}> <Col sizes={{ m: 3 }} style={{ ...introSliceColStyles, backgroundImage: 'url(/static/images/deck-left.jpg)', }} /> <Col sizes={{ m: 6 }} style={{ ...introSliceColStyles, padding: theme.baseSpacingUnit, backgroundImage: 'url(/static/images/deck-center.jpg)', backgroundColor: 'rgba(255, 255, 255, 0.3)', }} > <CornerBox style={{ paddingTop: theme.baseSpacingUnit * 2, paddingBottom: theme.baseSpacingUnit * 2, color: '#fff', }} > <Heading caps center style={{ fontSize: 28, fontWeight: 700, }} className="slice__title tk-rift" > All the latest news and updates </Heading> <p className="into-slice-p" style={{ margin: '0 auto 0', color: 'rgba(255, 255, 255, .8)', }} > Bringing together the latest news in competitive gaming, providing you with up to date information on tournaments, rosters, and esports news. </p> </CornerBox> </Col> <Col sizes={{ m: 3 }} style={{ ...introSliceColStyles, backgroundImage: 'url(/static/images/deck-right.jpg)', }} /> </Row> </Slice> <Slice name="favorite-games"> <Container> <Heading className="slice__title tk-rift" center style={{ marginBottom: theme.baseSpacingUnit }} > We've got your favorite games </Heading> <div className="slice__content"> <GameGrid games={games} /> </div> </Container> </Slice> <Slice name="teams"> <Container> <Heading className="slice__title tk-rift" center caps style={{ fontWeight: 700, marginBottom: theme.baseSpacingUnit }} > Latest News, Roster Changes, &amp; More </Heading> <ul className="logos-list"> <li> <a href="/"> <img src="/static/images/team-tl.png" alt="Team Liquid" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-fnc.png" alt="Fnatic" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-c9.png" alt="Cloud 9" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-tsm.png" alt="TSM" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-imt.png" alt="Immortals" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-og.png" alt="Optic Gaming" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-p1.png" alt="Pheonix1" /> </a> </li> </ul> <div className="slice__footer"> <Button href="/teams" variant="ghost" size="large"> Start Following Teams </Button> </div> </Container> </Slice> <Slice name="tournaments" textAlign="left"> <Container> <Row style={{ alignItems: 'center' }}> <Col sizes={{ m: 6 }}> <CornerBox variant="dark" style={{ display: 'inline-block' }}> <LazyLoad offset={100} height={300}> <img src="/static/images/tournaments-lol.jpg" alt="Final Round keeps you up to date with eSports tournaments" /> </LazyLoad> </CornerBox> </Col> <Col sizes={{ m: 6 }}> <Heading className="slice__title tk-rift"> Catch the Latest Pro Matches </Heading> <p> Stay up-to-date with your favorite teams and players in the biggest tournaments and matches. </p> <Button href="/tournaments" size="large"> Get Tournament Info </Button> </Col> </Row> </Container> </Slice> </PageContent> <style jsx>{` .logos-list { display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: ${theme.baseSpacingUnit}px; } .logos-list img { max-width: 75px; } :global(.slice--teams) { background-color: rgba(4, 19, 59, 1); background-image: url(${require('../static/images/banner-teams-small.jpg')}); background-size: cover; color: #fff; } @media (max-width: 599px) { .logos-list > li { flex: 0 50%; } } @media (max-width: ${theme.breakpoints.l - 1}px) { .logos-list { flex-flow: wrap; } .logos-list > li { flex: 0 33.33%; } .logos-list > li:last-child { margin: auto; } } @media (min-width: ${theme.breakpoints.sm}px) { .logos-list { margin-bottom: ${theme.baseSpacingUnit * 2}px; } } @media (min-width: ${theme.breakpoints.m}px) { :global(.slice--teams) { background-image: url(${require('../static/images/banner-teams.jpg')}); } .intro-slice-p { max-width: 75%; } .logos-list img { max-width: 110px; } } `}</style> </Page> ); }; export default Index;
src/routes/error/index.js
AntonyKwok/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ error }) { return { title: error.name, description: error.message, component: <ErrorPage error={error} />, status: error.status || 500, }; }, };
information/blendle-frontend-react-source/app/modules/issue/components/Region.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'components/Link'; function getStyle({ region }) { return { left: `${region.position[0]}%`, right: `${100 - region.position[2]}%`, top: `${region.position[1]}%`, bottom: `${100 - region.position[3]}%`, position: 'absolute', }; } const Region = ({ region, onClick, onMouseMove, onMouseLeave, onMouseEnter, url }) => ( <Link href={url} className="v-page-item-region" style={getStyle({ region })} onClick={onClick} onMouseEnter={onMouseEnter} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} analytics={{ type: 'page' }} /> ); Region.propTypes = { region: PropTypes.object.isRequired, onClick: PropTypes.func, onMouseMove: PropTypes.func, onMouseLeave: PropTypes.func, onMouseEnter: PropTypes.func, url: PropTypes.string.isRequired, }; export default Region; // WEBPACK FOOTER // // ./src/js/app/modules/issue/components/Region.js
src/components/upload-form.js
coding-lemur/nodefilestore
import React from 'react'; import Dropzone from 'react-dropzone'; import AddFilesButton from './add-files-button'; import EmptyFiles from './empty-files'; import FilesList from './files-list'; import FilesActionArea from './files-action-area'; import ResultContainer from './result-container'; import DataService from '../helper/data-service'; import FileViewModel from '../viewmodels/file.viewmodel'; export default class UploadForm extends React.Component { static get defaultState() { return { files: [], uploading: false, uploadFinished: false, apiResult: { downloadUrl: '', expirationDate: '', token: '' } }; } constructor(props) { super(props); this.state = UploadForm.defaultState; } render() { let filesNode; let resultContainerNode; let filesActionAreaNode; if (this.state.files.length > 0) { // has files filesNode = ( <FilesList files={this.state.files} showDeleteButtons={!(this.state.uploading || this.state.uploadFinished)} onDeleteFile={this.handleDeleteFile.bind(this)} /> ); if (this.state.uploadFinished) { resultContainerNode = ( <ResultContainer apiResult={this.state.apiResult} /> ); } else { // upload not finished filesActionAreaNode = ( <FilesActionArea disabled={this.state.uploading} onClearFiles={this.handleClearFiles.bind(this)} onUploadFiles={this.handleFilesUpload.bind(this)} /> ); } } else { // hasn't files filesNode = <EmptyFiles />; } return ( <Dropzone disableClick className="drop-zone" activeClassName="drag-over" rejectClassName="drop-rejected" onDrop={this.onDrop.bind(this)}> <div className="upload-form container"> {filesNode} {resultContainerNode} {filesActionAreaNode} <AddFilesButton disabled={this.state.uploading} onFilesAdded={this.handleFilesAdded.bind(this)} /> </div> </Dropzone> ); } handleFilesAdded(files) { if (this.state.uploadFinished) { // reset view const newState = UploadForm.defaultState; newState.files = files; this.setState(newState); } else { // add files to current queue this.setState({ files: this.state.files.concat(files) }); } } handleFilesUpload() { const dataService = new DataService(); const notify = (file, fileIndex) => { const newFiles = this.state.files; newFiles[fileIndex] = file; this.setState({ files: newFiles }); }; this.setState({ uploading: true }); dataService.uploadFiles(this.state.files, notify) .then((response) => { // upload finished this.setState({ uploading: false, uploadFinished: true, apiResult: { downloadUrl: response.downloadUrl, expirationDate: response.expirationDate, token: response.token } }); }, (error) => { console.error(error); this.setState({ uploading: false }); }); } handleClearFiles() { this.setState({ files: [] }); } handleDeleteFile(file) { if (!file) { return; } const files = this.state.files; const index = files.indexOf(file); if (index > -1) { files.splice(index, 1); this.setState({ files: files }); } } onDrop(files) { this.handleFilesAdded(files.map(file => { return new FileViewModel(file); })); } }
newclient/scripts/components/modal/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import ReactModal from 'react-modal'; import React from 'react'; import styles from './style'; export default function(props) { const onClose = props.onRequestClose !== undefined ? props.onRequestClose : () => {}; return ( <ReactModal isOpen={props.isOpen !== undefined ? props.isOpen : true} onRequestClose={onClose} className={styles.modal} overlayClassName={styles.overlay} style={props.style !== undefined ? props.style : undefined} > <div className={styles.top}> <i className={`fa fa-times ${styles.closeIcon}`} aria-hidden="true" onClick={onClose} /> </div> {props.children ? props.children : null} </ReactModal> ); }
rallyboard-v2/client/src/LoadingStatus.js
tylerjw/rallyscores
import React, { Component } from 'react'; import { Progress, Segment, Header } from 'semantic-ui-react'; class LoadingStatus extends Component { render() { const { status } = this.props; let percent = 0; if (status === 'started') { percent = 25; } else if (status === 'pending') { percent = 50; } else if (status === 'running') { percent = 75; } else if (status === 'finished') { percent = 100; } return ( <Segment> <Header>Updating results</Header> <Progress percent={percent} indicating > Job status: {status} </Progress> </Segment> ); } } export default LoadingStatus;
redux/todoList/src/main.js
yuanzhaokang/myAwesomeSimpleDemo
import AppContainer from './appContainer'; import ReactDOM from 'react-dom'; import React from 'react'; ReactDOM.render(<AppContainer />, document.getElementById('app'));
app/src/components/Footer/Social/index.js
AlexandreBourdeaudhui/abourdeaudhui.fr
/* * Package Import */ import React from 'react'; /* * Local Import */ /* * Code */ const links = [ { label: 'Twitter', url: 'https://twitter.com/qlex_', img: '/images/twitter.svg', }, { label: 'LinkedIn', url: 'https://www.linkedin.com/in/alexandrebourdeaudhui/', img: '/images/linkedin.svg', }, { label: 'Github', url: 'https://github.com/alexandrebourdeaudhui', img: '/images/github.svg', }, ]; /* * Component */ const Social = () => ( <div id="footer-container-social"> {links.map(link => ( <span className="footer-social-items" key={link.label}> <a href={link.url}> <img alt={`Lien ${link.label}`} className="footer-social-items-image" src={link.img} /> </a> </span> ))} </div> ); /* * Export */ export default Social;
src/components/Sidebar/Contacts/Contacts.js
ryanermita/ryanermita.github.io
// @flow strict import React from 'react'; import { getContactHref, getIcon } from '../../../utils'; import Icon from '../../Icon'; import styles from './Contacts.module.scss'; type Props = { contacts: { [string]: string, }, }; const Contacts = ({ contacts }: Props) => ( <div className={styles['contacts']}> <ul className={styles['contacts__list']}> {Object.keys(contacts).map((name) => (!contacts[name] ? null : ( <li className={styles['contacts__list-item']} key={name}> <a className={styles['contacts__list-item-link']} href={getContactHref(name, contacts[name])} rel="noopener noreferrer" target="_blank" > <Icon name={name} icon={getIcon(name)} /> </a> </li> )))} </ul> </div> ); export default Contacts;
modules/experimental/AsyncProps.js
jeffreywescott/react-router
import React from 'react'; import invariant from 'invariant'; var { func, array, shape, object } = React.PropTypes; var contextTypes = { asyncProps: shape({ reloadComponent: func, propsArray: array, componentsArray: array }) }; var _serverPropsArray = null; function setServerPropsArray(array) { invariant(!_serverPropsArray, 'You cannot call AsyncProps.hydrate more than once'); _serverPropsArray = array; } export function _clearCacheForTesting() { _serverPropsArray = null; } function hydrate(routerState, cb) { var { components, params } = routerState; var flatComponents = filterAndFlattenComponents(components); loadAsyncProps(flatComponents, params, cb); } function eachComponents(components, iterator) { for (var i = 0, l = components.length; i < l; i++) { if (typeof components[i] === 'object') { for (var key in components[i]) { iterator(components[i][key], i, key); } } else { iterator(components[i], i); } } } function filterAndFlattenComponents(components) { var flattened = []; eachComponents(components, function(Component) { if (Component.loadProps) flattened.push(Component); }); return flattened; } function loadAsyncProps(components, params, cb) { var propsArray = []; var componentsArray = []; var canceled = false; var needToLoadCounter = components.length; components.forEach(function(Component, index) { Component.loadProps(params, function(error, props) { needToLoadCounter--; propsArray[index] = props; componentsArray[index] = Component; maybeFinish(); }); }); function maybeFinish() { if (canceled === false && needToLoadCounter === 0) cb(null, {propsArray, componentsArray}); } return { cancel () { canceled = true; } }; } function getPropsForComponent(Component, componentsArray, propsArray) { var index = componentsArray.indexOf(Component); return propsArray[index]; } function mergeAsyncProps(current, changes) { for (var i = 0, l = changes.propsArray.length; i < l; i++) { let Component = changes.componentsArray[i]; let position = current.componentsArray.indexOf(Component); let isNew = position === -1; if (isNew) { current.propsArray.push(changes.propsArray[i]); current.componentsArray.push(changes.componentsArray[i]); } else { current.propsArray[position] = changes.propsArray[i]; } } } function arrayDiff(previous, next) { var diff = []; for (var i = 0, l = next.length; i < l; i++) if (previous.indexOf(next[i]) === -1) diff.push(next[i]); return diff; } function shallowEqual(a, b) { var key; var ka = 0; var kb = 0; for (key in a) { if (a.hasOwnProperty(key) && a[key] !== b[key]) return false; ka++; } for (key in b) if (b.hasOwnProperty(key)) kb++; return ka === kb; } var RouteComponentWrapper = React.createClass({ contextTypes: contextTypes, // this is here to meet the case of reloading the props when a component's params change, // the place we know that is here, but the problem is we get occasional waterfall loads // when clicking links quickly at the same route, AsyncProps doesn't know to load the next // props until the previous finishes rendering. // // if we could tell that a component needs its props reloaded in AsyncProps instead of here // (by the arrayDiff stuff in componentWillReceiveProps) then we wouldn't need this code at // all, and we coudl get rid of the terrible forceUpdate hack as well. I'm just not sure // right now if we can know to reload a pivot transition. componentWillReceiveProps(nextProps, context) { var paramsChanged = !shallowEqual( this.props.routerState.routeParams, nextProps.routerState.routeParams ); if (paramsChanged) { this.reloadProps(nextProps.routerState.routeParams); } }, reloadProps(params) { this.context.asyncProps.reloadComponent( this.props.Component, params || this.props.routerState.routeParams, this ); }, render() { var { Component, routerState } = this.props; var { componentsArray, propsArray, loading } = this.context.asyncProps; var asyncProps = getPropsForComponent(Component, componentsArray, propsArray); return <Component {...routerState} {...asyncProps} loading={loading} reloadAsyncProps={this.reloadProps} />; } }); var AsyncProps = React.createClass({ statics: { hydrate: hydrate, rehydrate: setServerPropsArray, createElement(Component, state) { return typeof Component.loadProps === 'function' ? <RouteComponentWrapper Component={Component} routerState={state}/> : <Component {...state}/>; } }, childContextTypes: contextTypes, getChildContext() { return { asyncProps: Object.assign({ reloadComponent: this.reloadComponent, loading: this.state.previousProps !== null }, this.state.asyncProps), }; }, getInitialState() { return { asyncProps: { propsArray: _serverPropsArray, componentsArray: _serverPropsArray ? filterAndFlattenComponents(this.props.components) : null, }, previousProps: null }; }, componentDidMount() { var initialLoad = this.state.asyncProps.propsArray === null; if (initialLoad) { hydrate(this.props, (err, asyncProps) => { this.setState({ asyncProps }); }); } }, componentWillReceiveProps(nextProps) { var routerTransitioned = nextProps.location !== this.props.location; if (!routerTransitioned) return; var oldComponents = this.props.components; var newComponents = nextProps.components; var components = arrayDiff( filterAndFlattenComponents(oldComponents), filterAndFlattenComponents(newComponents) ); if (components.length === 0) return; this.loadAsyncProps(components, nextProps.params); }, beforeLoad(cb) { this.setState({ previousProps: this.props }, cb); }, afterLoad(err, asyncProps, cb) { this.inflightLoader = null; mergeAsyncProps(this.state.asyncProps, asyncProps); this.setState({ previousProps: null, asyncProps: this.state.asyncProps }, cb); }, loadAsyncProps(components, params, cb) { if (this.inflightLoader) { this.inflightLoader.cancel(); } this.beforeLoad(() => { this.inflightLoader = loadAsyncProps(components, params, (err, asyncProps) => { this.afterLoad(err, asyncProps, cb); }); }); }, reloadComponent(Component, params, instance) { this.loadAsyncProps([Component], params, () => { // gotta fix this hack ... change in context doesn't cause the // RouteComponentWrappers to rerender (first one will because // of cloneElement) if (instance.isMounted()) instance.forceUpdate(); }); }, render() { var { route } = this.props; var { asyncProps, previousProps } = this.state; var initialLoad = asyncProps.propsArray === null; if (initialLoad) return route.renderInitialLoad ? route.renderInitialLoad() : null; else if (previousProps) return React.cloneElement(previousProps.children, { loading: true }); else return this.props.children; } }); export default AsyncProps;
src/svg-icons/action/copyright.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCopyright = (props) => ( <SvgIcon {...props}> <path d="M10.08 10.86c.05-.33.16-.62.3-.87s.34-.46.59-.62c.24-.15.54-.22.91-.23.23.01.44.05.63.13.2.09.38.21.52.36s.25.33.34.53.13.42.14.64h1.79c-.02-.47-.11-.9-.28-1.29s-.4-.73-.7-1.01-.66-.5-1.08-.66-.88-.23-1.39-.23c-.65 0-1.22.11-1.7.34s-.88.53-1.2.92-.56.84-.71 1.36S8 11.29 8 11.87v.27c0 .58.08 1.12.23 1.64s.39.97.71 1.35.72.69 1.2.91 1.05.34 1.7.34c.47 0 .91-.08 1.32-.23s.77-.36 1.08-.63.56-.58.74-.94.29-.74.3-1.15h-1.79c-.01.21-.06.4-.15.58s-.21.33-.36.46-.32.23-.52.3c-.19.07-.39.09-.6.1-.36-.01-.66-.08-.89-.23-.25-.16-.45-.37-.59-.62s-.25-.55-.3-.88-.08-.67-.08-1v-.27c0-.35.03-.68.08-1.01zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ActionCopyright = pure(ActionCopyright); ActionCopyright.displayName = 'ActionCopyright'; ActionCopyright.muiName = 'SvgIcon'; export default ActionCopyright;
src/svg-icons/content/flag.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFlag = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ContentFlag = pure(ContentFlag); ContentFlag.displayName = 'ContentFlag'; ContentFlag.muiName = 'SvgIcon'; export default ContentFlag;
node_modules/react-bootstrap/es/NavItem.js
skinsshark/skinsshark.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: React.PropTypes.bool, disabled: React.PropTypes.bool, role: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var disabled = _props.disabled; var onClick = _props.onClick; var className = _props.className; var style = _props.style; var props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
src/decorators.js
rgerstenberger/nuka-carousel
'use strict'; import React from 'react'; const DefaultDecorators = [ { component: React.createClass({ render() { return ( <button style={this.getButtonStyles(this.props.currentSlide === 0)} onClick={this.props.previousSlide}>PREV</button> ) }, getButtonStyles(disabled) { return { border: 0, background: 'rgba(0,0,0,0.4)', color: 'white', padding: 10, outline: 0, opacity: disabled ? 0.3 : 1, cursor: 'pointer' } } }), position: 'CenterLeft' }, { component: React.createClass({ render() { return ( <button style={this.getButtonStyles(this.props.currentSlide + this.props.slidesToScroll >= this.props.slideCount)} onClick={this.props.nextSlide}>NEXT</button> ) }, getButtonStyles(disabled) { return { border: 0, background: 'rgba(0,0,0,0.4)', color: 'white', padding: 10, outline: 0, opacity: disabled ? 0.3 : 1, cursor: 'pointer' } } }), position: 'CenterRight' }, { component: React.createClass({ render() { var self = this; var indexes = this.getIndexes(self.props.slideCount, self.props.slidesToScroll); return ( <ul style={self.getListStyles()}> { indexes.map(function(index) { return ( <li style={self.getListItemStyles()} key={index}> <button style={self.getButtonStyles(self.props.currentSlide === index)} onClick={self.props.goToSlide.bind(null, index)}> &bull; </button> </li> ) }) } </ul> ) }, getIndexes(count, inc) { var arr = []; for (var i = 0; i < count; i += inc) { arr.push(i); } return arr; }, getListStyles() { return { position: 'relative', margin: 0, top: -10, padding: 0 } }, getListItemStyles() { return { listStyleType: 'none', display: 'inline-block' } }, getButtonStyles(active) { return { border: 0, background: 'transparent', color: 'black', cursor: 'pointer', padding: 10, outline: 0, fontSize: 24, opacity: active ? 1 : 0.5 } } }), position: 'BottomCenter' } ]; export default DefaultDecorators;
src/app/views/myRecipes.js
nazar/soapee-ui
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import { Link } from 'react-router'; import meStore from 'stores/me'; import meActions from 'actions/me'; import RecipeListItem from 'components/recipeListItem'; import Spinner from 'components/spinner'; export default React.createClass( { mixins: [ Reflux.connect( meStore, 'profile' ) ], componentDidMount() { meActions.getMyRecipes(); }, render() { document.title = 'Soapee - My Recipes'; return ( <div id="my-recipes"> <legend>My Recipes</legend> { this.renderLoading() } { this.renderRecipes() } </div> ); }, renderLoading() { if ( !(this.state.profile.myRecipes) ) { return <Spinner />; } }, renderRecipes() { let lengthRecipes = _.get(this.state.profile.myRecipes, 'length', 0); if ( lengthRecipes > 0 ) { return _( this.state.profile.myRecipes ) .sortBy( 'created_at' ) .reverse() .map( this.renderRecipe ) .value(); } else if ( lengthRecipes === 0 ) { return ( <div className="jumbotron"> No recipes found. Use the <Link to="calculator">calculator</Link> to add recipes to your profile. </div> ); } }, renderRecipe( recipe ) { return ( <div key={ `recipe-${ recipe.id }` }> <RecipeListItem recipe={recipe} /> </div> ); } } );
.storybook/LoginStories.js
buaya91/just-us-blog
import React from 'react' import { storiesOf, action } from '@kadira/storybook' import LoginForm from '../src/login/LoginForm' import LoginPopUp from '../src/login/LoginPopUp' import { actions } from './testProps' storiesOf('Login', module) .add('form only', () => ( <LoginForm /> )) .add('with Popup', () => ( <LoginPopUp actions={actions} show /> ))
packages/material-ui-icons/src/ExpandLess.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z" /></g> , 'ExpandLess');
imports/ui/containers/AdminContainer.js
scimusmn/map-stories
/** * Container for the admin view where we control and manage image data */ // import React from 'react'; import { Meteor } from 'meteor/meteor'; import { composeWithTracker } from 'react-komposer'; import { Loading } from '../components/loading.js'; import { Images } from '../../api/images/images.js'; import { ImageFiles } from '../../api/imageFiles/imageFiles'; import { Places } from '../../api/places/places.js'; import AdminListWrapper from '../components/AdminListWrapper'; /** * Provide data for the list of places and images */ const composer = (props, onData) => { // Create a subscription of places and images const subscription = Meteor.subscribe('placesImages'); if (subscription.ready()) { const places = Places.find({}).fetch(); const images = Images.find({}).fetch(); const imageFiles = ImageFiles.find({}).fetch(); onData(null, { places, images, imageFiles }); } }; export default composeWithTracker(composer, Loading)(AdminListWrapper);
src/js/modules/Home.js
fredyagomez/reactjs-D3-V4-grommet
import React from 'react'; import Section from 'grommet/components/Section'; import Tiles from 'grommet/components/Tiles'; import Tile from 'grommet/components/Tile'; import Header from 'grommet/components/Header'; import Footer from 'grommet/components/Footer'; import Image from 'grommet/components/Image'; import NavLink from './NavLink'; export default React.createClass({ contextTypes: { router: React.PropTypes.object }, handleSubmit(event) { event.preventDefault(); const path = `/Taxonomy`; this.context.router.push(path); }, handleSubmit2(event) { event.preventDefault(); const path = `/Discovery`; this.context.router.push(path); }, handleSubmit3(event) { event.preventDefault(); const path = `/Policy`; this.context.router.push(path); }, handleSubmit4(event) { event.preventDefault(); //const userName = event.target.elements[0].value; //const repo = event.target.elements[1].value; const path = `/Change`; //const path = `/repos/${userName}/${repo}`; console.log(path); this.context.router.push(path); }, handleSubmit5(event) { event.preventDefault(); const path = `/Support`; //const path = `/repos/${userName}/${repo}`; console.log(path); this.context.router.push(path); }, render() { return ( <div> <Section align="start" pad={{"horizontal": "medium", "vertical": "medium", "between": "small"}} > <Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal" responsive={true}> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit}> <Header> <NavLink to="/Taxonomy"> <b>Tile 1</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_data.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit2}> <Header> <NavLink to="/Discovery"> <b>Tile 2</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> </Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal" > <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_ux.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit3}> <Header> <NavLink to="/Policy"> <b>Tile 3</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_demos.jpg" /> </Tile> </Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal"> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit4}> <Header> <NavLink to="/Change"> <b>Tile 4</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_strategy.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit5}> <Header> <NavLink to="/Support"> <b>Tile 5</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> </Tiles> </Tiles> </Section> </div>); } });
src/components/CompanyAndJobTitle/WorkExperiences/ExperienceEntry.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import cn from 'classnames'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import faLock from '@fortawesome/fontawesome-free-solid/faLock'; import { Heading, P } from 'common/base'; import i from 'common/icons'; import styles from './WorkExperiences.module.css'; import { formatSalary, formatSalaryRange } from 'common/formatter'; import { formatCreatedAt, formatWeekWorkTime } from './helper'; const createLinkTo = ({ pageType, id }) => ({ pathname: `/experiences/${id}`, state: { pageType }, }); const SNIPPET_SIZE = 30; const ExperienceEntry = ({ pageType, data: { id, company: { name: companyName } = {}, job_title: { name: jobTitle } = {}, created_at: createdAt, sections: [section], week_work_time: weekWorkTime, salary, recommend_to_others: recommendToOthers, }, size, canView, }) => ( <div className={cn(styles.container, styles[size])}> <Link to={createLinkTo({ id, pageType })}> <section className={styles.contentWrapper}> <div className={styles.labels}> <P size="s" className={styles.date}> 工作經驗 · {formatCreatedAt(createdAt)} </P> <div className={styles.salaryRecommendWrapper}> {weekWorkTime && canView && ( <div className={styles.weekWorkTime}> <i.Clock /> {formatWeekWorkTime(weekWorkTime)} </div> )} {salary && ( <div className={cn(styles.salary, { [styles.locked]: !canView, })} > {canView ? ( <React.Fragment> <i.Coin /> {formatSalary(salary)} </React.Fragment> ) : ( <React.Fragment> <FontAwesomeIcon icon={faLock} /> {formatSalaryRange(salary)} </React.Fragment> )} </div> )} <div className={styles.recommendToOthers}> {recommendToOthers === 'yes' ? <i.Good /> : <i.Bad />} {recommendToOthers === 'yes' ? '推' : '不推'} </div> </div> </div> <Heading Tag="h2" size={size === 'l' ? 'sl' : 'sm'} className={styles.heading} > {companyName} {jobTitle} </Heading> <div className={styles.snippetWrapper}> <span className={styles.snippet}> {section.content.slice(0, SNIPPET_SIZE)}.... </span> <span className={cn(styles.readmore, { [styles.locked]: !canView, })} > {`閱讀更多${canView ? '' : '並解鎖'}`} </span> </div> </section> </Link> </div> ); ExperienceEntry.propTypes = { data: PropTypes.object.isRequired, size: PropTypes.oneOf(['s', 'm', 'l']), canView: PropTypes.bool.isRequired, }; ExperienceEntry.defaultProps = { size: 'm', }; export default ExperienceEntry;
src/components/type-list.js
tylerchilds/pokedex
import React from 'react'; import TypeLink from '../components/type-link'; import ALL_TYPES from '../data/types'; export default class TypeList extends React.Component { render() { return ( <div> {ALL_TYPES.map((type, key) => ( <TypeLink type={type} key={key} /> ))} </div> ); } }
src/client/assets/js/features/driver/components/Data/Data.js
me-box/databox-sdk
import React from 'react'; import DataType from './DataType'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { actionCreators as driverActions, selector } from '../../'; @connect(selector, (dispatch) => { return{ actions: bindActionCreators(driverActions, dispatch), } }) export default class Data extends React.Component { constructor(props){ super(props); this.state={showdatatypes:false, add:false} this.renderDataTypes = this.renderDataTypes.bind(this); this.renderSchema = this.renderSchema.bind(this); this.addSchema = this.addSchema.bind(this); } addSchema(id){ if (this.state.add){ this.props.actions.addSchema(id); } this.setState({showdatatypes:false, add:false}); } renderDataTypes(){ const {driver:{dataTypes}} = this.props; const items = dataTypes.map((id)=>{ return <DataType key={id} id={id} addSchema={this.addSchema}/> }) return <div className="modal"> <div className="modal-content"> <div className="modal-header"> <span className="close" onClick={()=>this.setState({showdatatypes:false})}>&times;</span> <h2>select data type</h2> </div> <div className="modal-body"> <div className="datagrid"> {items} </div> </div> <div className="modal-footer"> </div> </div> </div> } renderSchema(){ const {driver:{schema}} = this.props; const addnew = <tr> <td><input type="text" placeholder="field name"/></td> <td> <div className="option"> <label onClick={()=>this.setState({showdatatypes:true, add:true})}>field type</label> </div> </td> <td> <div className="optionsgrid"> <div className="option"><label>blank</label></div> <div className="option"><input type="text" placeholder="0"/></div> <div className="option"><label>fn</label></div> <div className="option"><input type="text" placeholder="fn"/></div> <div className="option"><span className="close">&times;</span></div> </div> </td> </tr> const existing = schema.map((s,i)=>{ return <tr key={i}> <td><input type="text" placeholder="field name"/></td> <td> <div className="option"> <label onClick={()=>this.setState({showdatatypes:true, add:false})}>{s.schema.name}</label> </div> </td> <td> <div className="optionsgrid"> <div className="option"><label>blank</label></div> <div className="option"><input type="text" placeholder="0"/></div> <div className="option"><label>fn</label></div> <div className="option"><input type="text" placeholder="fn"/></div> <div className="option"><span className="close">&times;</span></div> </div> </td> </tr> }); const rows = [...existing, addnew]; return <table className="drivertable"> <thead> <tr> <th> field name </th> <th> type </th> <th> options </th> </tr> </thead> <tbody> {rows} </tbody> </table> } render(){ return <div> <div className="panel"> <div className="cell"> <div className="description"> Use this to describe the <strong>structure</strong> of the data that is emitted from your driver. This schema will also be used to create synthetic <strong> test data </strong> to test the driver in the sdk. </div> <div className="attribute"> {this.renderSchema()} </div> </div> </div> <div className="panel"> <div className="cell"> <div className="description"> Data <strong>format</strong> </div> <div className="attribute"> <div className="attribute-grid"> <div className="driverbutton">JSON</div> <div className="driverbutton">XML</div> <div className="driverbutton">CSV</div> </div> </div> </div> </div> <div className="panel"> <div className="cell"> <div className="description"> Data <strong>frequency</strong> </div> <div className="attribute"> </div> </div> </div> {this.state.showdatatypes && this.renderDataTypes()} </div> } }
src/Parser/DemonHunter/Shared/Modules/Items/SoulOfTheSlayer.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import ItemLink from 'common/ItemLink'; import SPECS from 'common/SPECS'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE'; const debug = false; /** * Equip: Gain one of the following talents based on your specialization: * Havoc: First Blood * Vengeance: Fallout */ class SoulOfTheSlayer extends Analyzer { static dependencies = { combatants: Combatants, }; on_initialized() { this.active = this.combatants.selected.hasFinger(ITEMS.SOUL_OF_THE_SLAYER.id); //Checks which spec has the ring equipped and then sets option1 or option2 accordingly - aswell as sets up the check for if they've picked another talent switch (this.combatants.selected.spec) { case SPECS.HAVOC_DEMON_HUNTER: this.talentGained = SPELLS.FIRST_BLOOD_TALENT.id; this.option1 = SPELLS.CHAOS_CLEAVE_TALENT.id; this.option2 = SPELLS.BLOODLET_TALENT.id; break; case SPECS.VENGEANCE_DEMON_HUNTER: this.talentGained = SPELLS.FALLOUT_TALENT.id; this.option1 = SPELLS.FEAST_OF_SOULS_TALENT.id; this.option2 = SPELLS.BURNING_ALIVE_TALENT.id; break; default: debug && console.log(' NO SPEC DETECTED'); break; } this.hasPickedOtherTalent = this.combatants.selected.hasTalent(this.option1) || this.combatants.selected.hasTalent(this.option2); } item() { return { item: ITEMS.SOUL_OF_THE_SLAYER, result: <Wrapper>This gave you <SpellLink id={this.talentGained} icon />.</Wrapper>, }; } get suggestionThresholds() { return { actual: this.hasPickedOtherTalent, isEqual: false, style: 'boolean', }; } suggestions(when) { when(this.suggestionThresholds).isFalse().addSuggestion((suggest) => { return suggest(<Wrapper>When using <ItemLink id={ITEMS.SOUL_OF_THE_SLAYER.id} /> please make sure to pick another talent in the talent row. Your choices are <SpellLink id={this.option1} /> or <SpellLink id={this.option2} />.</Wrapper>) .icon(ITEMS.SOUL_OF_THE_SLAYER.icon) .staticImportance(SUGGESTION_IMPORTANCE.MAJOR); }); } } export default SoulOfTheSlayer;
bdocker/bnodejs/gatsby/web/pages/less.js
waterbolik/prestudy
import React from 'react' import './example.less' import Helmet from 'react-helmet' import { config } from 'config' export default class Less extends React.Component { render () { return ( <div> <Helmet title={`${config.siteTitle} | Hi lessy friends`} /> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
pootle/static/js/auth/components/AuthContent.js
ta2-1/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import assign from 'object-assign'; import React from 'react'; import { PureRenderMixin } from 'react-addons-pure-render-mixin'; const AuthContent = React.createClass({ propTypes: { children: React.PropTypes.node, style: React.PropTypes.object, }, mixins: [PureRenderMixin], render() { // FIXME: use flexbox when possible const outer = assign({ display: 'table', height: '22em', width: '100%', }, this.props.style); const style = { outer, inner: { display: 'table-cell', verticalAlign: 'middle', }, }; return ( <div style={style.outer}> <div style={style.inner}> {this.props.children} </div> </div> ); }, }); export default AuthContent;
examples/with-why-did-you-render/scripts/wdyr.js
flybayer/next.js
import React from 'react' if (process.env.NODE_ENV === 'development') { if (typeof window !== 'undefined') { const whyDidYouRender = require('@welldone-software/why-did-you-render') whyDidYouRender(React, { trackAllPureComponents: true, }) } }
app/containers/DevTools.js
Kahrstrom/skillocate-react
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> );
packages/material-ui-icons/src/BatteryCharging80Sharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M17 4h-3V2h-4v2H7v5h4.93L13 7v2h4V4z" /><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v13h10V9h-4v3.5z" /></React.Fragment> , 'BatteryCharging80Sharp');
packages/stdind/src/main.js
istarkov/pbl
import { AppContainer } from 'react-hot-loader'; import { Observable } from 'rxjs'; import React from 'react'; import { render } from 'react-dom'; import webfontloader from 'webfontloader'; import setObservableConfig from 'recompose/setObservableConfig'; import 'normalize.css/normalize.css'; import './main.sass'; import App from './App'; const mountNode = document.getElementById('app'); setObservableConfig({ fromESObservable: Observable.from, }); webfontloader.load({ google: { families: ['Roboto Mono'], }, }); render( <AppContainer> <App /> </AppContainer>, mountNode, ); if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; // eslint-disable-line render( <AppContainer> <NextApp /> </AppContainer>, mountNode, ); }); }
src/pages/Login.js
prodigalyijun/demo-by-antd
import React from 'react'; import { Icon, Form, Input, Button, message } from 'antd'; import { post } from '../utils/request'; import style from '../styles/login-page.less'; const FormItem = Form.Item; class Login extends React.Component { constructor() { super(); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { post('http://localhost:3000/login', values) .then((res) => { if (res) { message.info('登录成功'); this.context.router.push('/'); } else { message.info('登录失败,账号或密码错误'); } }); } }); } render() { const { form } = this.props; const { getFieldDecorator } = form; return ( <div className={style.wrapper}> <div className={style.body}> <header className={style.header}>ReactManager </header> <section className={style.form}> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('account', { rules: [ { required: true, message: '请输入管理员账号', type: 'string' } ] })( <Input type="text" addonBefore={<Icon type="user" />} /> )} </FormItem> <FormItem> {getFieldDecorator('password', { rules: [ { required: true, message: '请输入密码', type: 'string' } ] })( <Input type="password" addonBefore={<Icon type="lock" />} /> )} </FormItem> <Button className={style.btn} type="primary" htmlType="submit">Sign In</Button> </Form> </section> </div> </div> ); } } Login.contextTypes = { router: React.PropTypes.object.isRequired }; Login = Form.create()(Login); export default Login;
src/containers/Forms/FormsWithValidation/index.js
EncontrAR/backoffice
import React, { Component } from 'react'; import Form from '../../../components/uielements/form'; import Input from '../../../components/uielements/input'; import PageHeader from '../../../components/utility/pageHeader'; import Box from '../../../components/utility/box'; import LayoutWrapper from '../../../components/utility/layoutWrapper'; import IntlMessages from '../../../components/utility/intlMessages'; const FormItem = Form.Item; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 5 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 12 }, }, }; export default class FormsWithValidation extends Component { render() { return ( <LayoutWrapper> <PageHeader>{<IntlMessages id="forms.formsWithValidation.header" />}</PageHeader> <Box> <Form> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.failLabel" />} validateStatus="error" help={<IntlMessages id="forms.formsWithValidation.failHelp" />} > <Input placeholder="unavailable choice" id="error" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.warningLabel" />} validateStatus="warning" > <Input placeholder="Warning" id="warning" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.ValidatingLabel" />} hasFeedback validateStatus="validating" help={<IntlMessages id="forms.formsWithValidation.ValidatingHelp" />} > <Input placeholder="I'm the content is being validated" id="validating" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.SuccessLabel" />} hasFeedback validateStatus="success" > <Input placeholder="I'm the content" id="success" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.WarninghasFeedbackLabel" />} hasFeedback validateStatus="warning" > <Input placeholder="Warning" id="warning" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.FailhasFeedbackLabel" />} hasFeedback validateStatus="error" help={<IntlMessages id="forms.formsWithValidation.FailhasFeedbackHelp" />} > <Input placeholder="unavailable choice" id="error" /> </FormItem> </Form> </Box> </LayoutWrapper> ); } }
examples/named-components/render/client.js
dlmr/react-router-redial
import { useRedial } from 'react-router-redial'; import React from 'react'; import { render } from 'react-dom'; import { Router, browserHistory, applyRouterMiddleware } from 'react-router'; // Render the app client-side to a given container element: export default (container, routes) => { const forcePageReloadOnError = true; const goBackOnError = false; // Function that can be used as a setting for useRedial function onError(err, { abort, beforeTransition, reason, router }) { if (process.env.NODE_ENV !== 'production') { console.error(reason, err); } // We only what to do this if it was a blocking hook that failed if (beforeTransition) { if (forcePageReloadOnError && reason === 'other') { window.location.reload(); } else if (goBackOnError && reason !== 'location-changed') { router.goBack(); } // Abort current loading automatically abort(); } } const component = ( <Router history={browserHistory} routes={routes} render={applyRouterMiddleware(useRedial({ beforeTransition: ['fetch'], afterTransition: ['defer', 'done'], parallel: true, initialLoading: () => <div>Loading…</div>, onError, }))} /> ); // Render app to container element: render(component, container); };
src/client.js
createspb/obsvtr
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; import makeRouteHooksSafe from './helpers/makeRouteHooksSafe'; const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), createHistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <ReduxRouter routes={getRoutes(store)} /> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__) { const DevTools = require('./components/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
packages/wix-style-react/src/ContactItemBuilder/ContactItemBuilder.js
wix/wix-style-react
import React from 'react'; import { classes } from './ContactItemBuilder.st.css'; import Avatar from '../Avatar/Avatar'; import Text from '../Text'; import { dataHooks } from './ContactItemBuilderDataHooks'; import PropTypes from 'prop-types'; import deprecationLog from '../utils/deprecationLog'; export const ContactItem = props => { deprecationLog( 'This component is deprecated. Please use ListItemSelect instead', ); return ( <div className={classes.contactItemOption}> <div className={classes.avatar}> <Avatar name={props.title} size="size30" imgProps={{ src: props.imageUrl }} data-hook={dataHooks.pickerOptionAvatar} /> </div> <div className={classes.contactItemTitles}> <Text ellipsis size="medium" weight="normal" secondary={!props.selected} light={props.selected} dataHook={dataHooks.pickerOptionTitle} > {props.title} </Text> {props.subtitle ? ( <Text ellipsis size="small" weight="thin" secondary={!props.selected} light={props.selected} dataHook={dataHooks.pickerOptionSubtitle} > {props.subtitle} </Text> ) : null} </div> </div> ); }; ContactItem.propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string, imageUrl: PropTypes.string, }; export const contactItemBuilder = ({ id, title, subtitle, imageUrl, disabled, }) => ({ id, disabled, value: ({ selected }) => ( <ContactItem title={title} subtitle={subtitle} imageUrl={imageUrl} selected={selected} /> ), });
src/containers/Contact/index.js
benceg/dani
import React from 'react'; import { asyncConnect } from 'redux-connect'; import get from 'lodash/get'; import Color from 'color'; import { componentWillMount } from 'react-lifecycle-decorators'; import { fetchContent, resetForm, sendForm } from './actions'; import ReactMarkdown from 'react-markdown'; import Helmet from 'react-helmet'; import AppView from '../../components/AppView'; import Main from '../../components/Main'; import Sidebar from '../../components/Sidebar'; import Image from '../../components/Image'; import ContactForm from '../../components/ContactForm'; import routerLink from '../../helpers/routerLink'; if (process.env.WEBPACK) require('./stylesheet.styl'); const tint = '#41396b'; const handleSubmit = (dispatch) => (fields) => dispatch(sendForm(fields)); const Contact = ({ body, image, title, error, sent, dispatch }) => <AppView className='Contact' tint={tint} title={title}> <Helmet meta={[{name: 'og:image', content: `${get(image, 'fields.file.url')}?fit=thumb&w=600&h=600`}]} style={[{cssText: `.Contact [type="submit"] { background-color: ${Color(tint).darken(0.5).hexString()}; }`}]} /> <Main> <Image alt={title} src={get(image, 'fields.file.url')} /> </Main> <Sidebar tint={tint}> <article> <h1>{title}</h1> <section> <ReactMarkdown source={body || ''} escapeHtml={true} renderers={{Link: routerLink}} /> </section> {error && <p className='error-message'>Sorry, there was a problem sending your form.</p>} {sent && <p className='success-message'>Thank you for your message.</p>} {!sent && <ContactForm action='/send' method='post' handleSubmit={handleSubmit(dispatch)} />} </article> </Sidebar> </AppView> Contact.propTypes = { loaded: React.PropTypes.bool.isRequired, body: React.PropTypes.string, image: React.PropTypes.object, title: React.PropTypes.string.isRequired, sent: React.PropTypes.bool, error: React.PropTypes.bool }; const mapStateToProps = ({ contact }) => ({ loaded: contact.loaded, body: contact.content.body, image: contact.content.image, title: contact.content.title, sent: contact.sent, error: contact.error }); export default asyncConnect( [{ promise: ({ store: { dispatch } }) => dispatch(fetchContent()) }], mapStateToProps )(componentWillMount(({ dispatch }) => dispatch(resetForm()))(Contact));
src/components/LayerStylesCarousel/LayerStyleItem.js
MinisterioPublicoRJ/inLoco-2.0
import React from 'react' const LayerStyleItem = ({layer, style, index, onStyleClick}) => { let itemClassName = 'layer-styles-carousel--list-item' if (layer && layer.selectedLayerStyleId === index) { itemClassName += ' selected' } function styleClick() { return onStyleClick(layer, index) } return ( <li className={itemClassName} onClick={styleClick}> { style ? <img className="layer-styles-carousel--image" src={style.thumb} alt={style.title}/> : '' } </li> ) } export default LayerStyleItem
pkg/interface/link/src/js/components/lib/channel-sidebar.js
jfranklin9000/urbit
import React, { Component } from 'react'; import { Route, Link } from 'react-router-dom'; import { GroupItem } from './group-item'; import { SidebarInvite } from '/components/lib/sidebar-invite'; import { Welcome } from '/components/lib/welcome'; import { alphabetiseAssociations } from '../../lib/util'; export class ChannelsSidebar extends Component { // drawer to the left render() { const { props, state } = this; let sidebarInvites = Object.keys(props.invites) .map((uid) => { return ( <SidebarInvite uid={uid} invite={props.invites[uid]} api={props.api} /> ); }); let associations = !!props.associations.contacts ? alphabetiseAssociations(props.associations.contacts) : {}; let groupedChannels = {}; [...props.listening].map((path) => { let groupPath = !!props.associations.link[path] ? props.associations.link[path]["group-path"] : ""; if (groupPath.startsWith("/~/")) { if (groupedChannels["/~/"]) { let array = groupedChannels["/~/"]; array.push(path); groupedChannels["/~/"] = array; } else { groupedChannels["/~/"] = [path]; }; } if (groupPath in associations) { if (groupedChannels[groupPath]) { let array = groupedChannels[groupPath]; array.push(path); groupedChannels[groupPath] = array; } else { groupedChannels[groupPath] = [path]; } } }); let selectedGroups = !!props.selectedGroups ? props.selectedGroups : []; let i = -1; const groupedItems = Object.keys(associations) .filter((each) => { if (selectedGroups.length === 0) { return true; }; let selectedPaths = selectedGroups.map((e) => { return e[0]; }); return selectedPaths.includes(each); }) .map((each) => { let channels = groupedChannels[each]; if (!channels || channels.length === 0) return; i++; if ((selectedGroups.length === 0) && groupedChannels["/~/"] && groupedChannels["/~/"].length !== 0) { i++; } return ( <GroupItem key={i} index={i} association={associations[each]} linkMetadata={props.associations["link"]} channels={channels} selected={props.selected} links={props.links} /> ) }); if ((selectedGroups.length === 0) && groupedChannels["/~/"] && groupedChannels["/~/"].length !== 0) { groupedItems.unshift( <GroupItem key={"/~/"} index={0} association={"/~/"} linkMetadata={props.associations["link"]} channels={groupedChannels["/~/"]} selected={props.selected} links={props.links} /> ) } let activeClasses = (this.props.active === "collections") ? " " : "dn-s "; let hiddenClasses = true; if (this.props.popout) { hiddenClasses = false; } else { hiddenClasses = this.props.sidebarShown; } return ( <div className={`bn br-m br-l br-xl b--gray4 b--gray1-d lh-copy h-100 flex-shrink-0 mw5-m mw5-l mw5-xl pt3 pt0-m pt0-l pt0-xl relative ` + activeClasses + ((hiddenClasses) ? "flex-basis-100-s flex-basis-30-ns" : "dn")}> <a className="db dn-m dn-l dn-xl f8 pb3 pl3" href="/">⟵ Landscape</a> <div className="overflow-y-scroll h-100"> <div className="w-100 bg-transparent"> <Link className="dib f9 pointer green2 gray4-d pa4" to={"/~link/new"}> New Collection </Link> </div> <Welcome associations={props.associations}/> {sidebarInvites} {groupedItems} </div> </div> ); } }
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
boneyao/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
src/layouts/index.js
btthomas/blakeandanna
import React from 'react' import PropTypes from 'prop-types' import Link from 'gatsby-link' import Helmet from 'react-helmet' import pages from '../pageList.js' import Burger from './burger.js' import './index.css' const Header = () => <div id="top-bar" style={{ marginBottom: '1rem', }} > <div style={{ margin: '0 auto', maxWidth: 960, padding: '1rem 0.5rem', }} > <div style={{display: 'inline-block', width: '85%'}}> <h1 style={{ margin: 0 }}> <Link to="/" style={{ color: '#fff', textDecoration: 'none', }} > Blake <span id="heart">♥</span> Anna </Link> </h1> <h2 style={{ margin: 0 }}> February 3, 2018 </h2> </div> <Burger> <Link to="/">home</Link> {pages.map(page => <Link key={page} to={`/${page}/`}>{page}</Link>)} </Burger> </div> </div> const TemplateWrapper = ({ children }) => <div> <Helmet title="Blake and Anna - February 3, 2018" meta={[ { name: 'description', content: 'Blake and Anna are getting married on February 3rd, 2018' }, ]} /> <Header /> <div style={{ margin: '0 auto', maxWidth: 960, padding: '0px 1.0875rem 1.45rem', paddingTop: 0, }} > {children()} </div> </div> TemplateWrapper.propTypes = { children: PropTypes.func, } export default TemplateWrapper
frontend/src/components/common/hoc/withCountryName.js
unicef/un-partner-portal
// eslint-disable-next-line import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const withCountryName = ComposedComponent => connect( (state, ownProps) => ({ countryName: state.countries[ownProps.code], }), )(ComposedComponent); withCountryName.propTypes = { countryName: PropTypes.string.isRequired, }; export default withCountryName;
src/components/input-group/InputGroupPrepend.js
ProAI/react-essentials
import React from 'react'; import PropTypes from 'prop-types'; import BaseView from '../../utils/rnw-compat/BaseView'; const propTypes = { children: PropTypes.node.isRequired, }; const InputGroupPrepend = React.forwardRef((props, ref) => ( <BaseView {...props} ref={ref} essentials={{ className: 'input-group-prepend' }} /> )); InputGroupPrepend.displayName = 'InputGroupPrepend'; InputGroupPrepend.propTypes = propTypes; export default InputGroupPrepend;
src/components/article/slideshow/thumbnails.js
hanyulo/twreporter-react
/*eslint-disable no-console*/ 'use strict' import classNames from 'classnames' import styles from './thumbnails.scss' import React from 'react' // lodash import get from 'lodash/get' import map from 'lodash/map' const defaultThumbnailWidth = 56 const Thumbnail = (props) => { const { alt, customClassName, greyOut, onThumbError, onThumbLoad, src, slideToIndex, thumbnailWidth } = props const _onEvent = (event) => { console.log(event.target.src) } let onError = typeof onThumbError === 'function' ? onThumbError : _onEvent let onLoad = typeof onThumbLoad === 'function' ? onThumbLoad : _onEvent return ( <li className={classNames(customClassName, styles['thumbnail'], greyOut ? styles['grey-out'] : '')} onClick={slideToIndex} onTouchStart={slideToIndex} > <img alt={alt} src={src} onError={onError} onLoad={onLoad} style={{ width: thumbnailWidth, height: thumbnailWidth }} /> </li> ) } const Thumbnails = (props) => { let { customClassName, currentIndex, thumbnails, thumbnailOffset, thumbnailWidth, onThumbError, onThumbLoad, slideToIndex, width } = props thumbnailWidth = thumbnailWidth || defaultThumbnailWidth const _slideToIndex = (index, event) => { slideToIndex(index, event) } let thumbnailComponents = map(thumbnails, (thumbnail, index) => { return ( <Thumbnail alt={thumbnail.alt} customClassName={thumbnail.customClassName} greyOut={currentIndex === index ? false : true} key={thumbnail.id} onThumbLoad={onThumbLoad} onThumbError={onThumbError} slideToIndex={_slideToIndex.bind(null, index)} src={thumbnail.src} thumbnailWidth={thumbnailWidth} /> ) }) let length = get(thumbnails, 'length', 0) // calculate how many thumbnails can show in the thumbnails conatiner let maximum = Math.floor((width - thumbnailOffset * (length - 1))/ thumbnailWidth) let translateX if (maximum > currentIndex) { translateX = 'translateX(0px)' } else { // current thumbnail is not shown in the thumbnails container translateX = `translateX(${-(currentIndex + 1 - maximum) * thumbnailWidth - thumbnailOffset * 2 }px)` } let style = { WebkitTransform: translateX, MozTransform: translateX, msTransform: translateX, OTransform: translateX, transform: translateX } return ( <ul className={classNames(styles['thumbnails'], maximum > length ? styles['flex-center'] : '',customClassName)} style={style}> {thumbnailComponents} </ul> ) } export default Thumbnails
frontend/src/Album/Search/AlbumInteractiveSearchModal.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import AlbumInteractiveSearchModalContent from './AlbumInteractiveSearchModalContent'; function AlbumInteractiveSearchModal(props) { const { isOpen, albumId, albumTitle, onModalClose } = props; return ( <Modal isOpen={isOpen} closeOnBackgroundClick={false} onModalClose={onModalClose} > <AlbumInteractiveSearchModalContent albumId={albumId} albumTitle={albumTitle} onModalClose={onModalClose} /> </Modal> ); } AlbumInteractiveSearchModal.propTypes = { isOpen: PropTypes.bool.isRequired, albumId: PropTypes.number.isRequired, albumTitle: PropTypes.string.isRequired, onModalClose: PropTypes.func.isRequired }; export default AlbumInteractiveSearchModal;
src/js/templates/index.js
julianburr/wp-react-theme
import React, { Component } from 'react'; import Header from '../components/header'; import Footer from '../components/footer'; import 'styles/index.scss'; export default class Index extends Component { render () { return ( <div className="wrap-all"> <Header /> <div className="content"> <div className="inner"> {this.props.children} </div> </div> <Footer /> </div> ); } }
src/svg-icons/device/screen-rotation.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenRotation = (props) => ( <SvgIcon {...props}> <path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/> </SvgIcon> ); DeviceScreenRotation = pure(DeviceScreenRotation); DeviceScreenRotation.displayName = 'DeviceScreenRotation'; DeviceScreenRotation.muiName = 'SvgIcon'; export default DeviceScreenRotation;
src/common/components/Button.js
sikhote/davidsinclair
// @flow import type { ColorProps, Theme } from '../themes/types'; import type { TextProps } from './Text'; import Box from './Box'; import React from 'react'; import Text, { computeTextStyle } from './Text'; import isReactNative from '../../common/app/isReactNative'; export type ButtonProps = ColorProps & TextProps & { // For blindness accessibility features. Consider making it mandatory. accessibilityLabel?: string, boxStyle?: (theme: Theme) => Object, children?: any, disabled?: boolean, onPress?: (e?: SyntheticMouseEvent) => any, outline?: boolean, textStyle?: (theme: Theme) => Object, }; type ButtonContext = { Button: () => React.Element<*>, theme: Theme, }; const Button = ({ as, accessibilityLabel, boxStyle, children, disabled, onPress, outline, textStyle, ...props }: ButtonProps, { Button: PlatformButton, theme, }: ButtonContext) => { const platformProps = isReactNative ? { accessibilityComponentType: 'button', accessibilityLabel, accessibilityTraits: ['button'], activeOpacity: theme.states.active.opacity, onPress, } : { onClick: onPress, }; const colorProps = Object.keys(theme.colors); // <Button primary // any is needed probably because Array find is not yet fully typed. const propColor: any = colorProps.find(color => props[color]); if (propColor) { props = { ...props, backgroundColor: propColor, bold: true, color: 'white', paddingHorizontal: 1, }; } // <Button primary outline if (propColor && outline) { delete props.backgroundColor; props = { ...props, bold: false, borderColor: props.backgroundColor, borderStyle: 'solid', borderWidth: 1, color: props.backgroundColor, paddingHorizontal: 1, }; } // Give button some vertical space. const { size = 0 } = props; if (size >= 0) { props = { marginVertical: 0.3, paddingVertical: 0.2, ...props, }; } else { props = { marginVertical: 0.5, ...props, }; if (props.borderWidth) { props = { // Ensure vertical Rhythm for Button size < 0. The lineHeight is the // only possible way how to do it. It doesn't work for multilines lineHeight: theme.typography.lineHeight - (2 * props.borderWidth), ...props, }; } } // Button consists of two components, Box and Text. That's because Button can // render not only text, but any component, and React Native Text can't // contain View based components. // Therefore, we have to split props for Box and props for Text. Fortunately, // that's what computeTextStyle does by design. It picks own props and return // the rest. We can also use boxStyle and textStyle props for further styling. const [computedTextStyle, allBoxProps] = computeTextStyle(theme, props); // To prevent "Unknown prop" warning, we have to remove color props. const boxProps = colorProps.reduce((props, prop) => { delete props[prop]; return props; }, allBoxProps); const childrenIsText = typeof children === 'string'; const { borderRadius = theme.button.borderRadius, } = props; return ( <Box as={as || PlatformButton} borderRadius={borderRadius} disabled={disabled} // Do we need that? flexDirection="row" justifyContent="center" opacity={disabled ? theme.states.disabled.opacity : 1} {...platformProps} {...boxProps} style={boxStyle} > {childrenIsText ? <Text // Pass backgroundColor to Text for maybeFixFontSmoothing function. backgroundColor={props.backgroundColor} style={theme => ({ ...computedTextStyle, ...(textStyle && textStyle(theme, computedTextStyle)), })} >{children}</Text> : children } </Box> ); }; Button.contextTypes = { Button: React.PropTypes.func, theme: React.PropTypes.object, }; export default Button;
examples/animations/app.js
mattydoincode/react-router
import React from 'react' import { render } from 'react-dom' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import StaticContainer from 'react-static-container' import { createHistory, useBasename } from 'history' import { Router, Route, Link } from 'react-router' require('./app.css') const history = useBasename(createHistory)({ basename: '/animations' }) /** * <RouteCSSTransitionGroup> renders twice on a route change. On the first * render, it "freezes" the transitioning-out component by setting * `shouldUpdate` on the <StaticContainer> to `false`. This prevents any * <Link>s nested under the old component from updating their active state to * reflect the new location, to allow for a smooth transition out. It then * renders the new, transitioning-in component immediately afterward. */ class RouteCSSTransitionGroup extends React.Component { constructor(props, context) { super(props, context) this.state = { previousPathname: null } } componentWillReceiveProps(nextProps, nextContext) { if (nextContext.location.pathname !== this.context.location.pathname) { this.setState({ previousPathname: this.context.location.pathname }) } } render() { const { children, ...props } = this.props const { previousPathname } = this.state return ( <ReactCSSTransitionGroup {...props}> <StaticContainer key={previousPathname || this.context.location.pathname} shouldUpdate={!previousPathname} > {children} </StaticContainer> </ReactCSSTransitionGroup> ) } componentDidUpdate() { if (this.state.previousPathname) { this.setState({ previousPathname: null }) } } } RouteCSSTransitionGroup.contextTypes = { location: React.PropTypes.object } class App extends React.Component { render() { return ( <div> <ul> <li><Link to="/page1">Page 1</Link></li> <li><Link to="/page2">Page 2</Link></li> </ul> <RouteCSSTransitionGroup component="div" transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500} > {this.props.children} </RouteCSSTransitionGroup> </div> ) } } class Page1 extends React.Component { render() { return ( <div className="Image"> <h1>Page 1</h1> <p><Link to="/page1" activeClassName="link-active">A link to page 1 should be active</Link>. Lorem ipsum dolor sit amet, consectetur adipisicing elit. <Link to="/page2" activeClassName="link-active">A link to page 2 should be inactive</Link>. Do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) } } class Page2 extends React.Component { render() { return ( <div className="Image"> <h1>Page 2</h1> <p>Consectetur adipisicing elit, sed do <Link to="/page2" activeClassName="link-active">a link to page 2 should also be active</Link> eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) } } render(( <Router history={history}> <Route path="/" component={App}> <Route path="page1" component={Page1} /> <Route path="page2" component={Page2} /> </Route> </Router> ), document.getElementById('example'))
src/parser/shared/modules/earlydotrefreshes/EarlyDotRefreshesSuggestionByCount.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import { SpellLink } from 'interface'; import React from 'react'; function suggest(when, suggestion) { when(suggestion).addSuggestion((suggest, actual, recommended) => suggest( <> You refreshed <SpellLink id={suggestion.spell.id} /> early {suggestion.count} times. The individual casts are highlighted on the timeline. </>, ) .icon(suggestion.spell.icon) .actual( t({ id: 'shared.suggestions.dots.countEarlyRefreshes', message: `${formatPercentage(actual)}% effective duration`, }), ) .recommended(`<${formatPercentage(recommended)}% is recommended`), ); } export default suggest;
src/components/Weather/Weather.js
andresol/sollieweb
import React from 'react' import { Link } from 'react-router' export class Weather extends React.Component { getTitle () { return this.title } getValue () { return this.name } render () { return ( <div> <h2>{this.getTitle()}</h2> <div className='live wind'>{this.getValue()}</div> <p> <Link /> </p> </div> ) } } Weather.defaultProps = { title: '' } Weather.propTypes = { getWeather: React.PropTypes.func, title: React.PropTypes.string, value: React.PropTypes.string } export class Wind extends Weather { constructor (props) { super(props) this.title = props.weather.name this.value = '' const { updateWind } = props.updateWind() if (updateWind) { updateWind() } } } // data[0].value Wind.defaultProps = { weather: { name: '', data: {} }, updateWind: () => '' } export class Temp extends Weather { constructor (props) { super(props) this.title = props.weather.name this.value = '' const { updateWind } = props.updateTemp() if (updateWind) { updateWind() } } } Temp.defaultProps = { weather: { name: '', data: [] }, updateTemp: () => '' }
assets/js/app.js
ChrisBr/duell-um-die-geld
import React from 'react'; import ReactDOM from 'react-dom'; import GameContainer from './react/gameContainer' window.jQuery = window.$ = require('../bower_components/jquery/dist/jquery.min.js'); //import bootstrapJs from '../bower_components/bootstrap/dist/js/bootstrap.min.js'; import bootstrapStyles from '../bower_components/bootstrap/dist/css/bootstrap.min.css'; $(function whenDomIsReady() { // as soon as this file is loaded, connect automatically, //var socket = io.sails.connect(); //window.socket = socket; ReactDOM.render( <GameContainer />, document.getElementById('root') ); });
imports/ui/components/header/header-notifications.js
irvinlim/free4all
import React from 'react'; import { browserHistory } from 'react-router'; import * as Colors from 'material-ui/styles/colors'; import Badge from 'material-ui/Badge'; import IconButton from 'material-ui/IconButton'; import Popover from 'material-ui/Popover'; import NotificationsList from './notifications-list'; import * as IconsHelper from '../../../util/icons'; export class HeaderNotifications extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } handleOnTouchTap(event) { event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); } handleRequestClose() { this.setState({ open: false }); } handleNotificationTouchTap(id, url) { const self = this; return function(event) { // Prevent ghost clicks event.preventDefault(); // Close the popover self.setState({ open: false }) // Set as read Herald.collection.update(id, { $set: { read: true } }); // Follow link if (url && url.length) { if (url.charAt(0) == "/") browserHistory.push(url); else window.location = url; } } } render() { if (!Meteor.user()) return <div />; else return ( <div id="header-notifications"> <Badge style={{ padding:0 }} badgeStyle={{ height: 20, width: 20, backgroundColor: 'rgba(255, 255, 255, 0.65)', color:'#045d68' }} badgeContent={ this.props.notificationCount }> <IconButton onTouchTap={ this.handleOnTouchTap.bind(this) } children={ IconsHelper.icon("notifications", { color: Colors.grey50 }) } /> </Badge> <Popover open={ this.state.open } anchorEl={ this.state.anchorEl } onRequestClose={ this.handleRequestClose.bind(this) } anchorOrigin={{"horizontal":"right","vertical":"bottom"}} targetOrigin={{"horizontal":"right","vertical":"top"}} style={{ maxWidth: 500, width: "calc(100% - 20px)", marginLeft: 10 }}> <NotificationsList notifications={ this.props.notifications } handleNotificationTouchTap={ this.handleNotificationTouchTap.bind(this) } /> </Popover> </div> ); } }
wisewit_front_end/public/js/userAuth/user_controller.js
emineKoc/WiseWit
'use strict' import React from 'react'; import SessionStore from './session_store.js'; import AuthActions from './auth_actions.js'; let UserControls = React.createClass({ handleLogout(e) { e.preventDefault(); AuthActions.logout(); }, render() { if (SessionStore.isLoggedIn()) { return ( <div className='UserControls'> <span>{SessionStore.getemail}</span> <a href='#' onClick={this.handleLogout}>Logout</span> </div> ); } else { return ( <div className='UserControls'> <a href='#/login'>Login</a> </div> ); } } }); export default UserControls;