path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/action/book.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBook = (props) => ( <SvgIcon {...props}> <path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/> </SvgIcon> ); ActionBook = pure(ActionBook); ActionBook.displayName = 'ActionBook'; ActionBook.muiName = 'SvgIcon'; export default ActionBook;
examples/js/selection/select-bgcolor-table.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); const selectRowProp = { mode: 'checkbox', bgColor: 'pink' }; export default class SelectBgColorTable extends React.Component { render() { return ( <BootstrapTable data={ products } selectRow={ selectRowProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
app/javascript/mastodon/features/compose/components/character_counter.js
anon5r/mastonon
import React from 'react'; import PropTypes from 'prop-types'; import { length } from 'stringz'; export default class CharacterCounter extends React.PureComponent { static propTypes = { text: PropTypes.string.isRequired, max: PropTypes.number.isRequired, }; checkRemainingText (diff) { if (diff < 0) { return <span className='character-counter character-counter--over'>{diff}</span>; } return <span className='character-counter'>{diff}</span>; } render () { const diff = this.props.max - length(this.props.text); return this.checkRemainingText(diff); } }
src/svg-icons/communication/stay-current-landscape.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape); CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape'; CommunicationStayCurrentLandscape.muiName = 'SvgIcon'; export default CommunicationStayCurrentLandscape;
src/svg-icons/action/settings-brightness.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBrightness = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02zM8 16h2.5l1.5 1.5 1.5-1.5H16v-2.5l1.5-1.5-1.5-1.5V8h-2.5L12 6.5 10.5 8H8v2.5L6.5 12 8 13.5V16zm4-7c1.66 0 3 1.34 3 3s-1.34 3-3 3V9z"/> </SvgIcon> ); ActionSettingsBrightness = pure(ActionSettingsBrightness); ActionSettingsBrightness.displayName = 'ActionSettingsBrightness'; ActionSettingsBrightness.muiName = 'SvgIcon'; export default ActionSettingsBrightness;
demo/src/Dialogs.js
kiloe/ui
import React from 'react'; import Doc from './Doc'; import View from '../../package/View'; export default class Dialogs extends React.Component { constructor(...args){ super(...args); this.state = {}; window.hideDialog = this.hide; } show = () => { this.setState({show: true}); } hide = () => { this.setState({show: false}); } render(){ let data = [ { title: 'Modal', clickToRun: true, src: Doc.jsx` <Modal id="modalexample" onClickOutside={stopDemo} pos={{bottom:50,right:50}}> <View pad accent> <Text>This is modal content</Text> <Text>Click anywhere to dismiss</Text> </View> </Modal> `, info:` You can render a Modal anywhere and it will display it's content overlayed on the screen. Modal is a low-level component for displaying overlay content. You probably want a Dialog really... ` }, { title: 'Modal', clickToRun: true, src: Doc.jsx` <Modal id="modalexample" shade pos={{top:100,left:50}}> <View pad accent> <Text>* Shade highlights the modal</Text> <Text>* Shade prevents click events</Text> <Button label="DISMISS" onClick={stopDemo} raised /> </View> </Modal> `, info:` Use 'shade' prop to dim the area the modal displays in and prevent clicks passing through. ` }, { title: 'Dialog', clickToRun: true, src: Doc.jsx` <Dialog id="dialogexample" pad> <Text title>Modal Dialog</Text> <Text>Any content can appear within a Dialog</Text> <Select radio required options={{'Yay Modals!':1,'Boo Modals':2}} value={1} /> <View row align="right"> <Button label="Continue" primary outline subtle onClick={stopDemo} /> </View> </Dialog> `, info:` Dialog is a common form of Modal, it shows it's content overlayed and raised on the screen, with a "shade". Simply render it somewhere to have it displayed. ` }, { title: 'Dialog in Dialog', clickToRun: true, src: Doc.jsx` <Dialog id="outter" shade> <Text>This is the outter dialog</Text> <Dialog id="inner" onClickOutside={stopDemo}> <Text>This inner dialog is displayed on top as it is nested within another dialog</Text> </Dialog> <Text>This is the outter dialog</Text> <Text>This is the outter dialog</Text> <Text>This is the outter dialog</Text> <Text>This is the outter dialog</Text> <Text>This is the outter dialog</Text> </Dialog> `, info:` Dialogs can be used within dialogs. The inner-most dialog will be on the top. ` }, { title: 'Tasty Snackbar - full width (mobile)', clickToRun: true, src: Doc.jsx` <Snackbar onClickOutside={stopDemo} id="outter" size="fill" text="This is a message" actionText="Undo" action={function() { console.log( "Undoing!" ); }} /> `, info:` Mmmm ` }, { title: 'Snackbar - floating (desktop)', clickToRun: true, src: Doc.jsx` <Snackbar onClickOutside={stopDemo} id="outter" size="intrinsic" text="This is a message" actionText="Undo" action={function() { console.log( "Undoing!" ); }} /> `, info:` ` }, { title: 'Snackbar without an action', clickToRun: true, src: Doc.jsx` <Snackbar onClickOutside={stopDemo} size="fill" id="outter" text="This is a longer message without any action." /> `, info:` ` }, ]; return ( <View scroll> <View> {data.map((x,i) => <Doc key={i} title={x.title} clickToRun={x.clickToRun} src={x.src}>{x.info}</Doc>)} </View> </View> ); } }
src/client.js
bdefore/universal-redux
import React from 'react'; import ReactDOM from 'react-dom'; import createStore from './shared/create'; import { render as renderDevtools } from './client/devtools'; // dependencies of external source. these resolve via webpack aliases // as assigned in merge-configs.js import middleware, { middlewareAppliedCallback } from 'universal-redux/middleware'; import createRootClientComponent from 'universal-redux/rootClientComponent'; const dest = document.getElementById('content'); const store = createStore(middleware, window.__data); const devComponent = renderDevtools(); if (middlewareAppliedCallback) { middlewareAppliedCallback(); } // There is probably no need to be asynchronous here createRootClientComponent(store, __PROVIDERS__, devComponent) .then((root) => { ReactDOM.render(root, 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.warn('WARNING: Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } }) .catch((err) => { console.error(err, err.stack); });
src/components/Notification/index.js
deep-c/react-redux-notify
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames/bind'; import styles from './Notification.scss'; export class Notification extends React.PureComponent { static propTypes = { id: PropTypes.number.isRequired, type: PropTypes.string.isRequired, canDismiss: PropTypes.bool.isRequired, duration: PropTypes.number.isRequired, icon: PropTypes.node, customStyles: PropTypes.object, customComponent: PropTypes.element, acceptBtn: PropTypes.shape({ handler: PropTypes.func.isRequired, icon: PropTypes.node, title: PropTypes.node, }), denyBtn: PropTypes.shape({ handler: PropTypes.func.isRequired, icon: PropTypes.node, title: PropTypes.node, }), isFirst: PropTypes.bool.isRequired, handleDismiss: PropTypes.func.isRequired, handleDismissAll: PropTypes.func.isRequired, localization: PropTypes.shape({ closeAllBtnText: PropTypes.string.isRequired, acceptBtnText: PropTypes.string.isRequired, denyBtnText: PropTypes.string.isRequired, }), showCloseAllBtn: PropTypes.bool, }; static defaultProps = { canDismiss: true, customStyles: {}, duration: 0, showCloseAllBtn: true, }; componentDidMount() { const { handleDismiss, id, duration } = this.props; if (duration !== 0) { setTimeout(() => { handleDismiss(id); }, duration); } } _getStyle(name) { return this.props.customStyles[name] || styles[name]; } render() { const { handleDismiss, handleDismissAll, isFirst, message, type, canDismiss, acceptBtn, denyBtn, icon, customStyles, id, localization, showCloseAllBtn, } = this.props; const cx = classNames.bind(Object.assign({}, styles, customStyles)); const containerTypeClass = cx({ 'has-close': !isFirst && canDismiss, 'no-close': !isFirst && !canDismiss, 'has-close-all': isFirst && canDismiss && showCloseAllBtn, 'has-close-all--noDismiss': isFirst && !canDismiss && showCloseAllBtn, [`notification--${type.toLowerCase()}`]: true, }); return ( <div className={containerTypeClass}> {icon ? <span className={styles.icon}>{icon}</span> : false} <div className={this._getStyle('content')}> <div className={this._getStyle('item__message')}>{message}</div> {!canDismiss && (acceptBtn || denyBtn) ? ( <div className={this._getStyle('item__btnBar')}> {acceptBtn ? ( <div className={this._getStyle('actionBtn')} onClick={(e) => { acceptBtn.handler(e, this.props); }} > {acceptBtn.icon && typeof acceptBtn.icon === 'string' ? ( <i className={acceptBtn.icon} /> ) : ( acceptBtn.icon )} {acceptBtn.title || localization.acceptBtnText} </div> ) : ( false )} {denyBtn ? ( <div className={this._getStyle('actionBtn')} onClick={(e) => { denyBtn.handler(e, this.props); }} > {denyBtn.icon && typeof denyBtn.icon === 'string' ? ( <i className={denyBtn.icon} /> ) : ( denyBtn.icon )} {denyBtn.title || localization.denyBtnText} </div> ) : ( false )} </div> ) : ( false )} </div> {canDismiss ? ( <div className={this._getStyle('close')} onClick={() => handleDismiss(id)} /> ) : ( false )} {isFirst && canDismiss && showCloseAllBtn ? ( <div className={this._getStyle('close-all')} onClick={() => handleDismissAll()} > {localization.closeAllBtnText} </div> ) : ( false )} </div> ); } } export default Notification;
client/src/components/ListGroup/ListGroupItem.js
silverstripe/silverstripe-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class ListGroupItem extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(event) { if (this.props.onClick) { this.props.onClick(event, this.props.onClickArg); } } render() { const className = `list-group-item ${this.props.className}`; return ( <a role="button" tabIndex={0} className={className} onClick={this.handleClick}> {this.props.children} </a> ); } } ListGroupItem.propTypes = { onClickArg: PropTypes.any, onClick: PropTypes.func, }; export default ListGroupItem;
examples/huge-apps/components/Dashboard.js
ksivam/react-router
import React from 'react' import { Link } from 'react-router' class Dashboard extends React.Component { render() { const { courses } = this.props return ( <div> <h2>Super Scalable Apps</h2> <p> Open the network tab as you navigate. Notice that only the amount of your app that is required is actually downloaded as you navigate around. Even the route configuration objects are loaded on the fly. This way, a new route added deep in your app will not affect the initial bundle of your application. </p> <h2>Courses</h2>{' '} <ul> {courses.map(course => ( <li key={course.id}> <Link to={`/course/${course.id}`}>{course.name}</Link> </li> ))} </ul> </div> ) } } export default Dashboard
docs/containers/callout/index.js
aruberto/react-foundation-components
import React from 'react'; import { Callout } from '../../../src/callout'; const CalloutPage = () => ( <div> <Callout> <h5>This is a callout.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="secondary"> <h5>This is a secondary panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="primary"> <h5>This is a primary panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="success"> <h5>This is a success panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="warning"> <h5>This is a warning panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="alert"> <h5>This is a alert panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="primary" size="small"> <h5>This is a primary panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> <Callout color="primary" size="large"> <h5>This is a primary panel.</h5> <p>It has an easy to override visual style, and is appropriately subdued.</p> <a href="#">It's dangerous to go alone, take this.</a> </Callout> </div> ); export default CalloutPage;
src/icons/IosToggle.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosToggle extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M128,320c-26.467,0-48,21.533-48,48s21.533,48,48,48s48-21.533,48-48S154.467,320,128,320z"></path> <path d="M383.5,272h-255C75.205,272,32,315.205,32,368.5S75.205,464,128.5,464h255c53.295,0,96.5-42.205,96.5-95.5 S436.795,272,383.5,272z M128,432c-35.346,0-64-28.653-64-64c0-35.346,28.654-64,64-64s64,28.654,64,64 C192,403.347,163.346,432,128,432z"></path> <path d="M384,192c26.467,0,48-21.533,48-48s-21.533-48-48-48s-48,21.533-48,48S357.533,192,384,192z"></path> <path d="M128.5,240h255c53.295,0,96.5-42.205,96.5-95.5S436.795,48,383.5,48h-255C75.205,48,32,91.205,32,144.5 S75.205,240,128.5,240z M384,80c35.346,0,64,28.654,64,64c0,35.347-28.654,64-64,64s-64-28.653-64-64 C320,108.654,348.654,80,384,80z"></path> </g> </g>; } return <IconBase> <g> <path d="M128,320c-26.467,0-48,21.533-48,48s21.533,48,48,48s48-21.533,48-48S154.467,320,128,320z"></path> <path d="M383.5,272h-255C75.205,272,32,315.205,32,368.5S75.205,464,128.5,464h255c53.295,0,96.5-42.205,96.5-95.5 S436.795,272,383.5,272z M128,432c-35.346,0-64-28.653-64-64c0-35.346,28.654-64,64-64s64,28.654,64,64 C192,403.347,163.346,432,128,432z"></path> <path d="M384,192c26.467,0,48-21.533,48-48s-21.533-48-48-48s-48,21.533-48,48S357.533,192,384,192z"></path> <path d="M128.5,240h255c53.295,0,96.5-42.205,96.5-95.5S436.795,48,383.5,48h-255C75.205,48,32,91.205,32,144.5 S75.205,240,128.5,240z M384,80c35.346,0,64,28.654,64,64c0,35.347-28.654,64-64,64s-64-28.653-64-64 C320,108.654,348.654,80,384,80z"></path> </g> </IconBase>; } };IosToggle.defaultProps = {bare: false}
src/pwa.js
prakash-u/react-redux
import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './helpers/Html'; export default function () { return `<!doctype html>${ReactDOM.renderToStaticMarkup(<Html />)}`; }
app/javascript/mastodon/containers/compose_container.js
increments/mastodon
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { hydrateStore } from '../actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; import Compose from '../features/standalone/compose'; import initialState from '../initial_state'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); if (initialState) { store.dispatch(hydrateStore(initialState)); } export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <Compose /> </Provider> </IntlProvider> ); } }
docs/app/Examples/elements/Rail/Variations/RailExampleAttachedInternal.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Image, Rail, Segment } from 'semantic-ui-react' const RailExampleAttachedInternal = () => ( <Segment> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> <Rail attached internal position='left'> <Segment>Left Rail Content</Segment> </Rail> <Rail attached internal position='right'> <Segment>Right Rail Content</Segment> </Rail> </Segment> ) export default RailExampleAttachedInternal
node_modules/semantic-ui-react/dist/es/collections/Message/MessageContent.js
SuperUncleCat/ServerMonitoring
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * A message can contain a content. */ function MessageContent(props) { var children = props.children, className = props.className; var classes = cx('content', className); var rest = getUnhandledProps(MessageContent, props); var ElementType = getElementType(MessageContent, props); return React.createElement( ElementType, _extends({}, rest, { className: classes }), children ); } MessageContent.handledProps = ['as', 'children', 'className']; MessageContent._meta = { name: 'MessageContent', parent: 'Message', type: META.TYPES.COLLECTION }; MessageContent.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string } : {}; export default MessageContent;
fields/types/markdown/MarkdownField.js
Adam14Four/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on jQuery */ // Scope jQuery and the bootstrap-markdown editor so it will mount var $ = require('jquery'); require('./lib/bootstrap-markdown'); // Append/remove ### surround the selection // Source: https://github.com/toopay/bootstrap-markdown/blob/master/js/bootstrap-markdown.js#L909 var toggleHeading = function (e, level) { var chunk; var cursor; var selected = e.getSelection(); var content = e.getContent(); var pointer; var prevChar; if (selected.length === 0) { // Give extra word chunk = e.__localize('heading text'); } else { chunk = selected.text + '\n'; } // transform selection and set the cursor into chunked text if ((pointer = level.length + 1, content.substr(selected.start - pointer, pointer) === level + ' ') || (pointer = level.length, content.substr(selected.start - pointer, pointer) === level)) { e.setSelection(selected.start - pointer, selected.end); e.replaceSelection(chunk); cursor = selected.start - pointer; } else if (selected.start > 0 && (prevChar = content.substr(selected.start - 1, 1), !!prevChar && prevChar !== '\n')) { e.replaceSelection('\n\n' + level + ' ' + chunk); cursor = selected.start + level.length + 3; } else { // Empty string before element e.replaceSelection(level + ' ' + chunk); cursor = selected.start + level.length + 1; } // Set the cursor e.setSelection(cursor, cursor + chunk.length); }; var renderMarkdown = function (component) { // dependsOn means that sometimes the component is mounted as a null, so account for that & noop if (!component.refs.markdownTextarea) { return; } var options = { autofocus: false, savable: false, resize: 'vertical', height: component.props.height, hiddenButtons: ['Heading'], // Heading buttons additionalButtons: [{ name: 'groupHeaders', data: [{ name: 'cmdH1', title: 'Heading 1', btnText: 'H1', callback: function (e) { toggleHeading(e, '#'); }, }, { name: 'cmdH2', title: 'Heading 2', btnText: 'H2', callback: function (e) { toggleHeading(e, '##'); }, }, { name: 'cmdH3', title: 'Heading 3', btnText: 'H3', callback: function (e) { toggleHeading(e, '###'); }, }, { name: 'cmdH4', title: 'Heading 4', btnText: 'H4', callback: function (e) { toggleHeading(e, '####'); }, }], }], // Insert Header buttons into the toolbar reorderButtonGroups: ['groupFont', 'groupHeaders', 'groupLink', 'groupMisc', 'groupUtil'], }; if (component.props.toolbarOptions.hiddenButtons) { var hiddenButtons = (typeof component.props.toolbarOptions.hiddenButtons === 'string') ? component.props.toolbarOptions.hiddenButtons.split(',') : component.props.toolbarOptions.hiddenButtons; options.hiddenButtons = options.hiddenButtons.concat(hiddenButtons); } $(component.refs.markdownTextarea).markdown(options); }; module.exports = Field.create({ displayName: 'MarkdownField', statics: { type: 'Markdown', getDefaultValue: () => ({}), }, // override `shouldCollapse` to check the markdown field correctly shouldCollapse () { return this.props.collapse && !this.props.value.md; }, // only have access to `refs` once component is mounted componentDidMount () { if (this.props.wysiwyg) { renderMarkdown(this); } }, // only have access to `refs` once component is mounted componentDidUpdate () { if (this.props.wysiwyg) { renderMarkdown(this); } }, renderField () { const styles = { padding: 8, height: this.props.height, }; const defaultValue = ( this.props.value !== undefined && this.props.value.md !== undefined ) ? this.props.value.md : ''; return ( <textarea className="md-editor__input code" defaultValue={defaultValue} name={this.getInputName(this.props.paths.md)} ref="markdownTextarea" style={styles} /> ); }, renderValue () { // TODO: victoriafrench - is this the correct way to do this? the object // should be creating a default md where one does not exist imo. const innerHtml = ( this.props.value !== undefined && this.props.value.md !== undefined ) ? this.props.value.md.replace(/\n/g, '<br />') : ''; return ( <FormInput dangerouslySetInnerHTML={{ __html: innerHtml }} multiline noedit /> ); }, });
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleStackable.js
aabustamante/Semantic-UI-React
import React from 'react' import { Grid, Image, Segment } from 'semantic-ui-react' const GridExampleStackable = () => ( <Grid stackable columns={2}> <Grid.Column> <Segment> <Image src='/assets/images/wireframe/paragraph.png' /> </Segment> </Grid.Column> <Grid.Column> <Segment> <Image src='/assets/images/wireframe/paragraph.png' /> </Segment> </Grid.Column> </Grid> ) export default GridExampleStackable
docs/pages/api-docs/accordion-details.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/accordion-details'; const requireRaw = require.context('!raw-loader!./', false, /\/accordion-details\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
src/components/Video/index.js
welovekpop/uwave-web-welovekpop.club
import cx from 'classnames'; import isEqual from 'is-equal-shallow'; import React from 'react'; import PropTypes from 'prop-types'; import screenfull from 'screenfull'; import injectMediaSources from '../../utils/injectMediaSources'; import VideoBackdrop from './VideoBackdrop'; import VideoProgressBar from './VideoProgressBar'; import VideoToolbar from './VideoToolbar'; import MouseMoveCapture from './VideoMouseMoveCapture'; import Player from '../Player'; const defaultSourceTools = () => null; const enhance = injectMediaSources(); class Video extends React.Component { static propTypes = { getMediaSource: PropTypes.func.isRequired, isFullscreen: PropTypes.bool, enabled: PropTypes.bool, size: PropTypes.string, volume: PropTypes.number, isMuted: PropTypes.bool, media: PropTypes.object, seek: PropTypes.number, onFullscreenEnter: PropTypes.func.isRequired, onFullscreenExit: PropTypes.func.isRequired, }; state = { shouldShowToolbar: false, }; componentDidMount() { if (screenfull.enabled) { screenfull.on('change', this.handleFullscreenChange); } } shouldComponentUpdate(nextProps) { return !isEqual(nextProps, this.props); } componentDidUpdate(prevProps) { const { isFullscreen } = this.props; if (prevProps.isFullscreen && !isFullscreen && screenfull.enabled) { // Checking for `enabled` here, because our props have probably changed // _after_ exiting fullscreen mode (see `this.handleFullscreenChange`). // This way we don't double-exit. if (screenfull.isFullscreen) { screenfull.exit(); } } } handleFullscreenEnter = () => { const { onFullscreenEnter } = this.props; if (screenfull.enabled) { screenfull.request(this.element); } onFullscreenEnter(); }; handleFullscreenChange = () => { const { onFullscreenExit } = this.props; if (!screenfull.isFullscreen) { onFullscreenExit(); } }; handleMouseMove = () => { if (this.timer) { clearTimeout(this.timer); } else { this.setState({ shouldShowToolbar: true }); } this.timer = setTimeout(this.handleMouseMoveEnd, 5000); }; handleMouseMoveEnd = () => { clearTimeout(this.timer); this.timer = null; this.setState({ shouldShowToolbar: false }); }; refElement = (element) => { this.element = element; }; render() { const { getMediaSource, isFullscreen, enabled, size, volume, isMuted, media, seek, onFullscreenExit, } = this.props; if (!media) { return <div className="Video" />; } const { shouldShowToolbar, } = this.state; const currentSource = getMediaSource(media.sourceType); const MediaSourceTools = (currentSource && currentSource.VideoTools) ? currentSource.VideoTools : defaultSourceTools; return ( <div ref={this.refElement} className={cx('Video', `Video--${media.sourceType}`, `Video--${size}`)} > <VideoBackdrop url={media.thumbnail} /> <Player enabled={enabled} size={size} volume={volume} isMuted={isMuted} media={media} seek={seek} /> {isFullscreen && ( <MouseMoveCapture active={shouldShowToolbar} onMouseMove={this.handleMouseMove} /> )} {isFullscreen && ( <VideoProgressBar media={media} seek={seek} /> )} {(!isFullscreen || shouldShowToolbar) && ( <VideoToolbar isFullscreen={isFullscreen} onFullscreenEnter={this.handleFullscreenEnter} onFullscreenExit={onFullscreenExit} > <MediaSourceTools media={media} /> </VideoToolbar> )} </div> ); } } export default enhance(Video);
src/browser/users/UsersPage.js
sikhote/davidsinclair
// @flow import OnlineUsers from './OnlineUsers'; import React from 'react'; import linksMessages from '../../common/app/linksMessages'; import { Box, PageHeader } from '../../common/components'; import { Title } from '../components'; const UsersPage = () => ( <Box> <Title message={linksMessages.users} /> <PageHeader heading="Users" description="Online users." /> <OnlineUsers /> </Box> ); export default UsersPage;
pootle/static/js/browser/components/TranslateActions.js
evernote/zing
/* * Copyright (C) Zing contributors. * * This file is a part of the Zing 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 React from 'react'; import { t } from 'utils/i18n'; import { getTranslateUrl } from 'utils/url'; import NumberPill from './NumberPill'; const Action = ({ caption, count, name, url }) => { const WrapperTag = url ? ({ children }) => ( <a className={name} href={url}> {children} </a> ) : ({ children }) => <span className={name}>{children}</span>; return ( <WrapperTag> <span className="caption">{caption}</span> <NumberPill n={count} /> </WrapperTag> ); }; Action.propTypes = { caption: React.PropTypes.string.isRequired, count: React.PropTypes.number.isRequired, name: React.PropTypes.string.isRequired, url: React.PropTypes.string, }; const TranslateActions = ({ areActionsEnabled, areDisabledItemsShown, pootlePath, stats, }) => { const { critical, suggestions, total, translated } = stats; return ( <ul> {critical > 0 && ( <li> <Action name="fix-errors" caption={ areActionsEnabled ? t('Fix critical errors') : t('Critical errors') } count={critical} url={ areActionsEnabled ? getTranslateUrl(pootlePath, { category: 'critical', includeDisabled: areDisabledItemsShown, }) : '' } /> </li> )} {suggestions > 0 && ( <li> <Action name="review-suggestions" caption={areActionsEnabled ? t('Review suggestions') : t('Suggestions')} count={suggestions} url={ areActionsEnabled ? getTranslateUrl(pootlePath, { filter: 'suggestions', includeDisabled: areDisabledItemsShown, }) : '' } /> </li> )} {total - translated > 0 && ( <li> <Action name="continue-translation" caption={ areActionsEnabled ? t('Continue translation') : t('Incomplete') } count={total - translated} url={ areActionsEnabled ? getTranslateUrl(pootlePath, { filter: 'incomplete', includeDisabled: areDisabledItemsShown, }) : '' } /> </li> )} {total > 0 && ( <li> <Action name="translation-complete" caption={areActionsEnabled ? t('View all') : t('All')} count={total} url={ areActionsEnabled ? getTranslateUrl(pootlePath, { includeDisabled: areDisabledItemsShown, }) : '' } /> </li> )} </ul> ); }; TranslateActions.propTypes = { canAdminDueDates: React.PropTypes.bool, initialDueDate: React.PropTypes.shape({ id: React.PropTypes.number, due_on: React.PropTypes.number, pootle_path: React.PropTypes.string, }), areDisabledItemsShown: React.PropTypes.bool.isRequired, areActionsEnabled: React.PropTypes.bool, pootlePath: React.PropTypes.string.isRequired, stats: React.PropTypes.shape({ critical: React.PropTypes.number, suggestions: React.PropTypes.number, total: React.PropTypes.number.isRequired, translated: React.PropTypes.number.isRequired, }), }; export default TranslateActions;
TGMeituan/Components/Common/HotView.js
targetcloud/Meituan
/** * Created by targetcloud on 2016/12/22. */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native'; var Dimensions = require('Dimensions'); var {width} = Dimensions.get('window'); var HotView = React.createClass({ getDefaultProps(){ return{ title:'', subTitle: '', rightIcon: '', titleColor: '', tplurl: '', callBackClickCell: null } }, render() { return ( <TouchableOpacity onPress={()=>this.clickCell(this.props.tplurl)}> <View style={{backgroundColor:'white',width:width * 0.25-1 ,height:119,marginBottom:1,marginRight:1,alignItems:'center',justifyContent:'center'}}> <Text style={{color:this.props.titleColor,fontSize:18,fontWeight:'bold'}}>{this.props.title}</Text> <Text style={{color:'gray'}}>{this.props.subTitle}</Text> <Image source={{uri: this.props.rightIcon}} style={{width:64,height:48, resizeMode:'contain'}}/> </View> </TouchableOpacity> ); }, clickCell(data){ if (this.props.tplurl == '') return; if (this.props.callBackClickCell == null) return; this.props.callBackClickCell(data); } }); module.exports = HotView;
src/components/pagination.js
asommer70/dvdpila.electron
// import React, { Component } from 'react'; import React from 'react'; const Pagination = ({pages, currentPage, handleClick}) => { console.log('pages:', pages); return ( <ul className="pagination text-center" role="navigation" aria-label="Pagination"> <li className="pagination-previous"><a href="#" aria-label="Previous page">Previous</a></li> {pages.map((page) => { return ( <li key={page}> <a href="#" className={(page + 1) == currentPage ? 'current' : ''} onClick={handleClick.bind(this, parseInt(page) + 1)} aria-label={'Page ' + (parseInt(page) + 1)} > {page + 1} </a> </li> ) })} <li className="pagination-next"><a href="#" aria-label="Next page">Next</a></li> </ul> ) }; export default Pagination; // export default class Pagination extends Component { // constructor(props) { // super(props); // console.log('Pagination props:', props); // } // // render() { // return ( // <ul className="pagination text-center" role="navigation" aria-label="Pagination"> // <li className="pagination-previous"><a href="#" aria-label="Previous page">Previous</a></li> // {this.props.pages.map((page) => { // return ( // <li key={page}> // <a href="#" // className={(page + 1) == this.props.currentPage ? 'current' : ''} // onClick={this.props.handleClick.bind(this)} // aria-label={'Page ' + (parseInt(page) + 1)} // > // {page + 1} // </a> // </li> // ) // })} // <li className="pagination-next"><a href="#" aria-label="Next page">Next</a></li> // </ul> // ) // } // }
src/components/app/App.js
gtdudu/hapi-wurb
import React from 'react'; import PropTypes from 'prop-types'; const App = ({ children }) => { return ( <div> {children} </div> ); }; App.propTypes = { children : PropTypes.object }; export default App;
src/searchbar/SearchBar-ios.js
martinezguillaume/react-native-elements
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Button, Dimensions, LayoutAnimation, UIManager, StyleSheet, View, ActivityIndicator, Text, } from 'react-native'; import Ionicon from 'react-native-vector-icons/Ionicons'; import ViewPropTypes from '../config/ViewPropTypes'; import Input from '../input/Input'; const SCREEN_WIDTH = Dimensions.get('window').width; const IOS_GRAY = '#7d7d7d'; class SearchBar extends Component { focus = () => { this.input.focus(); }; blur = () => { this.input.blur(); }; clear = () => { this.input.clear(); this.onChangeText(''); this.props.onClearText && this.props.onClearText(); }; cancel = () => { this.blur(); this.props.onCancel && this.props.onCancel(); }; onFocus = () => { this.props.onFocus && this.props.onFocus(); UIManager.configureNextLayoutAnimation && LayoutAnimation.easeInEaseOut(); this.setState({ hasFocus: true }); }; onBlur = () => { this.props.onBlur && this.props.onBlur(); UIManager.configureNextLayoutAnimation && LayoutAnimation.easeInEaseOut(); this.setState({ hasFocus: false }); }; onChangeText = text => { this.props.onChangeText && this.props.onChangeText(text); this.setState({ isEmpty: text === '' }); }; constructor(props) { super(props); this.state = { hasFocus: false, isEmpty: true, }; } render() { const { cancelButtonTitle, clearIcon, containerStyle, leftIcon, leftIconContainerStyle, rightIconContainerStyle, inputStyle, noIcon, placeholderTextColor, showLoading, loadingProps, ...attributes } = this.props; const { hasFocus, isEmpty } = this.state; const { style: loadingStyle, ...otherLoadingProps } = loadingProps; const searchIcon = ( <Ionicon size={20} name={'ios-search'} color={IOS_GRAY} /> ); return ( <View style={styles.container}> <Input {...attributes} onFocus={this.onFocus} onBlur={this.onBlur} onChangeText={this.onChangeText} ref={input => (this.input = input)} inputStyle={[styles.input, inputStyle]} containerStyle={[ styles.inputContainer, !hasFocus && { width: SCREEN_WIDTH - 32, marginRight: 15 }, containerStyle, ]} leftIcon={noIcon ? undefined : leftIcon ? leftIcon : searchIcon} leftIconContainerStyle={[ styles.leftIconContainerStyle, leftIconContainerStyle, ]} placeholderTextColor={placeholderTextColor} rightIcon={ <View style={{ flexDirection: 'row' }}> {showLoading && ( <ActivityIndicator style={[ clearIcon && !isEmpty && { marginRight: 10 }, loadingStyle, ]} {...otherLoadingProps} /> )} {clearIcon && !isEmpty && ( <Ionicon name={'ios-close-circle'} size={20} color={IOS_GRAY} onPress={() => this.clear()} /> )} </View> } rightIconContainerStyle={[ styles.rightIconContainerStyle, rightIconContainerStyle, ]} /> <Button title={cancelButtonTitle} onPress={this.cancel} /> </View> ); } } SearchBar.propTypes = { cancelButtonTitle: PropTypes.string, clearIcon: PropTypes.bool, loadingProps: PropTypes.object, noIcon: PropTypes.bool, showLoading: PropTypes.bool, onClearText: PropTypes.func, onCancel: PropTypes.func, containerStyle: ViewPropTypes.style, leftIcon: PropTypes.object, leftIconContainerStyle: ViewPropTypes.style, rightIconContainerStyle: ViewPropTypes.style, inputStyle: Text.propTypes.style, placeholderTextColor: PropTypes.string, }; SearchBar.defaultProps = { cancelButtonTitle: 'Cancel', clearIcon: true, loadingProps: {}, noIcon: false, showLoading: false, onClearText: null, onCancel: null, placeholderTextColor: IOS_GRAY, }; const styles = StyleSheet.create({ container: { width: SCREEN_WIDTH, backgroundColor: '#f5f5f5', paddingBottom: 13, paddingTop: 13, flexDirection: 'row', }, input: { flex: 1, marginLeft: 6, }, inputContainer: { borderBottomWidth: 0, backgroundColor: '#dcdce1', borderRadius: 9, height: 36, marginLeft: 15, }, rightIconContainerStyle: { marginRight: 8, }, leftIconContainerStyle: { marginLeft: 8, }, }); export default SearchBar;
docs/pages/api-docs/input.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/input'; const requireRaw = require.context('!raw-loader!./', false, /\/input\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
client/src/App.js
chi-bumblebees-2017/gnomad
import React, { Component } from 'react'; import './App.css'; import Conversation from './Conversation'; import Conversations from './Conversations'; import NewProfile from './NewProfile'; import NavBar from './NavBar'; import Login from './components/Login'; import Profile from './components/Profile'; import SearchContainer from './SearchContainer'; import Dashboard from './Dashboard'; import { BrowserRouter as Router, Route, NavLink, } from 'react-router-dom'; import Logout from './components/Logout'; import ActionCable from 'action-cable-react-jwt'; class App extends Component { constructor(props) { super(props); this.state = { cable: null, loggedIn: false, }; this.connectCable = this.connectCable.bind(this); this.disconnectCable = this.disconnectCable.bind(this); this.checkLogin = this.checkLogin.bind(this); this.setLoggedIn = this.setLoggedIn.bind(this); this.setLoggedOut = this.setLoggedOut.bind(this); } checkLogin() { return (localStorage.getItem('gnomad-auth-token') && localStorage.getItem('gnomad-auth-token').length >= 1) } setLoggedIn() { this.setState({ loggedIn: true, }) } setLoggedOut() { this.setState({ loggedIn: false, }) } componentDidMount() { if (this.checkLogin()) { this.connectCable(); this.setLoggedIn() } } componentWillUnmount() { this.state.cable.subscriptions.subscriptions.forEach((sub) => { this.state.cable.subscriptions.remove(sub) }) } connectCable() { let cableURL = "" if (window.location.href.includes("gnomad")){ cableURL = "wss://gnomad.herokuapp.com/cable" } else{ cableURL = "ws://localhost:3001/cable" } this.setState({ cable: ActionCable.createConsumer(cableURL, localStorage.getItem('gnomad-auth-token')), }) } disconnectCable() { this.setState({ cable: null, }) } render() { if (this.state.loggedIn) { return ( <Router> <div className="App"> <NavBar options={4}> <NavLink className="item" to="/account">Dashboard</NavLink> <NavLink className="item" to="/chats">Chats</NavLink> <NavLink className="item" to="/search">Search</NavLink> <NavLink className="item" to="/logout">Logout</NavLink> </NavBar> <Route exact path="/" render={props => <Login connectCable={this.connectCable} loginHandler={this.setLoggedIn} />} /> <Route exact path="/chats" render={props => <Conversations loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/chats/:id" render={props => <Conversation cable={this.state.cable} loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/register" render={props => <NewProfile loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/search" render={props => <SearchContainer loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/users/:name/:id" render={props => <Profile loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/logout" render={props => <Logout disconnectCable={this.disconnectCable} logoutHandler={this.setLoggedOut} {...props} />} /> <Route path="/account" render={props => <Dashboard loggedIn={this.state.loggedIn} {...props} />} /> </div> </Router> ); } else { return ( <Router> <div className="App"> <NavBar options={1}> <div></div> </NavBar> <Route exact path="/" render={props => <Login connectCable={this.connectCable} loginHandler={this.setLoggedIn} />} /> <Route exact path="/chats" render={props => <Conversations loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/chats/:id" render={props => <Conversation cable={this.state.cable} loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/register" render={props => <NewProfile loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/search" render={props => <SearchContainer loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/users/:name/:id" render={props => <Profile loggedIn={this.state.loggedIn} {...props} />} /> <Route path="/logout" render={props => <Logout disconnectCable={this.disconnectCable} logoutHandler={this.setLoggedOut} {...props} />} /> <Route path="/account" render={props => <Dashboard loggedIn={this.state.loggedIn} {...props} />} /> </div> </Router> ); } } } export default App;
src/icons/StrokeBasket.js
ipfs/webui
import React from 'react' const StrokeBasket = props => ( <svg viewBox='0 0 100 100' {...props}> <path d='M83.4 42.43h-6.89V27a8.77 8.77 0 0 0-8.32-8.75A3.46 3.46 0 0 0 64.74 15H40.09a3.47 3.47 0 0 0-3.45 3.23A8.78 8.78 0 0 0 28.32 27v15.43h-6.88c-3.46 0-6.27 3.3-6.27 7.35v1.85a7.61 7.61 0 0 0 3.35 6.48l3.65 20 .08.31C23.1 81.81 23.9 85 26.71 85h51.62c2.32 0 3.85-2.37 4.56-7l3.44-19.9a7.62 7.62 0 0 0 3.33-6.47v-1.85c0-4.05-2.81-7.35-6.26-7.35zm-43.78-24a.47.47 0 0 1 .47-.47h24.65a.47.47 0 0 1 .47.47v.3a1.06 1.06 0 0 0-.11.44 1 1 0 0 0 .11.43v1.45a.48.48 0 0 1-.47.47H40.09a.48.48 0 0 1-.47-.47zM30.32 27a6.79 6.79 0 0 1 6.3-6.75v.86a3.48 3.48 0 0 0 3.47 3.47h24.65a3.47 3.47 0 0 0 3.47-3.47v-.86a6.78 6.78 0 0 1 6.3 6.75v15.43H30.32zm49.61 50.51C79.39 81 78.53 82 78.33 82H26.72c-.55-.28-1.18-2.83-1.56-4.35l-3.94-21.44h62.39zm6.73-25.88A4.67 4.67 0 0 1 85 55.39v-.18H19.86v.18a4.67 4.67 0 0 1-1.69-3.76v-1.85c0-2.36 1.5-4.35 3.27-4.35h62c1.77 0 3.26 2 3.26 4.35z' /> <path d='M36.33 59.82h-.82a2.79 2.79 0 0 0-2.79 2.79v11.87a2.8 2.8 0 0 0 2.79 2.8h.82a2.8 2.8 0 0 0 2.79-2.8V62.61a2.79 2.79 0 0 0-2.79-2.79zm.79 14.66a.8.8 0 0 1-.79.8h-.82a.8.8 0 0 1-.79-.8V62.61a.79.79 0 0 1 .79-.79h.82a.79.79 0 0 1 .79.79zm15.7-14.66H52a2.79 2.79 0 0 0-2.79 2.79v11.87a2.8 2.8 0 0 0 2.79 2.8h.81a2.81 2.81 0 0 0 2.8-2.8V62.61a2.8 2.8 0 0 0-2.79-2.79zm.8 14.66a.8.8 0 0 1-.8.8H52a.79.79 0 0 1-.79-.8V62.61a.79.79 0 0 1 .79-.79h.81a.79.79 0 0 1 .8.79zm15.7-14.66h-.81a2.8 2.8 0 0 0-2.8 2.79v11.87a2.81 2.81 0 0 0 2.8 2.8h.81a2.8 2.8 0 0 0 2.79-2.8V62.61a2.79 2.79 0 0 0-2.79-2.79zm.79 14.66a.79.79 0 0 1-.79.8h-.81a.8.8 0 0 1-.8-.8V62.61a.79.79 0 0 1 .8-.79h.81a.79.79 0 0 1 .79.79z' /> </svg> ) export default StrokeBasket
example/src/app.js
derzunov/redux-react-i18n
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import { i18nReducer, i18nActions } from 'redux-react-i18n'; let reducers = {}; import { reducer as formReducer } from 'redux-form' reducers.form = formReducer; reducers.i18n = i18nReducer; import App from './components/App'; const store = createStore( combineReducers( reducers ) ); store.dispatch( i18nActions.setLanguages( [ { code: 'ru-RU', name: 'Русский' }, { code: 'en-US', name: 'English (USA)' }, { code: 'pl', name: 'Polish' }, { code: 'fr', name: 'French' }, { code: 'be', name: 'Белорусский' } ] ) ); store.dispatch( i18nActions.setDictionaries( { 'ru-RU': { 'key_1': 'Первый дефолтный ключ из установленного нами словаря', 'key_2': [ [ "Остался", "Осталось", "Осталось" ], " ", "$count", " ", [ "час", "часа", "часов" ] ], 'key_3': 'Просто число после двоеточия: $Count', 'key_4': { nested_1: 'Москва', nested_2: 'Санкт-Петербург' } }, 'en-US': { 'key_1': 'First default key from our dictionary', 'key_2': ["$count", " ", [ "hour", "hours"] ], 'key_3': 'Number: $Count', 'key_4': { nested_1: 'Moscow', nested_2: 'St. Petersburg' } }, 'pl': { 'key_1': 'Prosze, dwa bilety drugiej klasy do Warszawy.', 'key_2': [[ "Pozostała", "Pozostały", "Pozostało" ], " ", "$count", " ", [ "godzina", "godziny", "godzin" ] ], 'key_3': 'Numer: $Count', 'key_4': { nested_1: 'Moskwa', nested_2: 'Petersburg' } }, 'fr': { 'key_1': 'Ayant risqué une fois-on peut rester heureux toute la vie', 'key_2': ["$count", " ", [ "heure", "heures"], " ", [ "restante", "restantes"] ], 'key_3': 'Nombre: $Count', 'key_4': { nested_1: 'Moscou', nested_2: 'St. Pétersbourg' } }, 'be': { 'key_1': 'Адзін квіток да Мінска, калі ласка', 'key_2': [ [ "Засталася", "Засталося", "Засталося" ], " ", "$count", " ", [ "гадзіна", "гадзіны", "гадзін" ] ], 'key_3': 'Засталося: $Count', 'key_4': { nested_1: 'Масква', nested_2: 'Санкт-Пецярбург' } } } ) ); store.dispatch( i18nActions.setCurrentLanguage( 'ru-RU' ) ); function render () { ReactDOM.render( <Provider store={store}> <App></App> </Provider> , document.getElementById('root')); } render();
src/Col.js
zanjs/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const Col = React.createClass({ propTypes: { /** * The number of columns you wish to span * * for Extra small devices Phones (<768px) * * class-prefix `col-xs-` */ xs: React.PropTypes.number, /** * The number of columns you wish to span * * for Small devices Tablets (≥768px) * * class-prefix `col-sm-` */ sm: React.PropTypes.number, /** * The number of columns you wish to span * * for Medium devices Desktops (≥992px) * * class-prefix `col-md-` */ md: React.PropTypes.number, /** * The number of columns you wish to span * * for Large devices Desktops (≥1200px) * * class-prefix `col-lg-` */ lg: React.PropTypes.number, /** * Move columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-offset-` */ xsOffset: React.PropTypes.number, /** * Move columns to the right * * for Small devices Tablets * * class-prefix `col-sm-offset-` */ smOffset: React.PropTypes.number, /** * Move columns to the right * * for Medium devices Desktops * * class-prefix `col-md-offset-` */ mdOffset: React.PropTypes.number, /** * Move columns to the right * * for Large devices Desktops * * class-prefix `col-lg-offset-` */ lgOffset: React.PropTypes.number, /** * Change the order of grid columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-push-` */ xsPush: React.PropTypes.number, /** * Change the order of grid columns to the right * * for Small devices Tablets * * class-prefix `col-sm-push-` */ smPush: React.PropTypes.number, /** * Change the order of grid columns to the right * * for Medium devices Desktops * * class-prefix `col-md-push-` */ mdPush: React.PropTypes.number, /** * Change the order of grid columns to the right * * for Large devices Desktops * * class-prefix `col-lg-push-` */ lgPush: React.PropTypes.number, /** * Change the order of grid columns to the left * * for Extra small devices Phones * * class-prefix `col-xs-pull-` */ xsPull: React.PropTypes.number, /** * Change the order of grid columns to the left * * for Small devices Tablets * * class-prefix `col-sm-pull-` */ smPull: React.PropTypes.number, /** * Change the order of grid columns to the left * * for Medium devices Desktops * * class-prefix `col-md-pull-` */ mdPull: React.PropTypes.number, /** * Change the order of grid columns to the left * * for Large devices Desktops * * class-prefix `col-lg-pull-` */ lgPull: React.PropTypes.number, /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; let classes = {}; Object.keys(styleMaps.SIZES).forEach(function(key) { let size = styleMaps.SIZES[key]; let prop = size; let classPart = size + '-'; if (this.props[prop]) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Offset'; classPart = size + '-offset-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Push'; classPart = size + '-push-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Pull'; classPart = size + '-pull-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } }, this); return ( <ComponentClass {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </ComponentClass> ); } }); export default Col;
scripts/dashboard/components/ProjectForm/view.js
vedranjukic/dockerino
import React from 'react' import { FormControl, FormGroup, ControlLabel, HelpBlock, Button } from 'react-bootstrap'; import ProjectFormServiceList from './ProjectFormServiceList' import ProjectFormPortList from './ProjectFormPortList' function view (props, state) { const project = state.project if (!project) { return ( <div> Oops, something went wrong! Requested project is invalid. </div> ) } return ( <div> <form> <FormGroup controlId="formProjectName" validationState={null} > <ControlLabel>Project Name</ControlLabel> <FormControl type="text" value={project.name} placeholder="Enter text" /> <FormControl.Feedback /> <HelpBlock>Validation is based on string length.</HelpBlock> </FormGroup> <FormGroup controlId="formProjectStack" validationState={null} > <ControlLabel>Stack</ControlLabel> <FormControl componentClass="select" placeholder="select" value={project.stack}> <option value="select">Select Stack</option> <option value="node">NodeJS</option> <option value="php">PHP</option> <option value="ruby">Ruby</option> </FormControl> <ControlLabel>Version</ControlLabel> <FormControl componentClass="select" placeholder="select" value={project.version}> <option value="select">Select Version</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </FormControl> <FormControl.Feedback /> <HelpBlock>Validation is based on string length.</HelpBlock> </FormGroup> <FormGroup controlId="formProjectServiceList" validationState={null} > <ControlLabel>Services</ControlLabel> <ProjectFormServiceList project={project} /> </FormGroup> <FormGroup controlId="formProjectPortList" validationState={null} > <ControlLabel>Ports</ControlLabel> <ProjectFormPortList project={project} /> </FormGroup> <Button type="submit"> { project?'Update':'Create' } </Button> </form> </div> ) } export default view
src/components/Widgets/ListControl.js
dopry/netlify-cms
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { List, Map, fromJS } from 'immutable'; import { sortable } from 'react-sortable'; import FontIcon from 'react-toolbox/lib/font_icon'; import ObjectControl from './ObjectControl'; import styles from './ListControl.css'; function ListItem(props) { return <div {...props} className={`list-item ${ props.className }`}>{props.children}</div>; } ListItem.propTypes = { className: PropTypes.string, children: PropTypes.node, }; ListItem.displayName = 'list-item'; function valueToString(value) { return value ? value.join(',').replace(/,([^\s]|$)/g, ', $1') : ''; } const SortableListItem = sortable(ListItem); const valueTypes = { SINGLE: 'SINGLE', MULTIPLE: 'MULTIPLE', }; export default class ListControl extends Component { static propTypes = { onChange: PropTypes.func.isRequired, value: PropTypes.node, field: PropTypes.node, forID: PropTypes.string, getAsset: PropTypes.func.isRequired, onAddAsset: PropTypes.func.isRequired, onRemoveAsset: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { itemStates: Map(), value: valueToString(props.value) }; this.valueType = null; } componentDidMount() { const { field } = this.props; if (field.get('fields')) { this.valueType = valueTypes.MULTIPLE; } else if (field.get('field')) { this.valueType = valueTypes.SINGLE; } } componentWillUpdate(nextProps) { if (this.props.field === nextProps.field) return; if (nextProps.field.get('fields')) { this.valueType = valueTypes.MULTIPLE; } else if (nextProps.field.get('field')) { this.valueType = valueTypes.SINGLE; } } handleChange = (e) => { const { onChange } = this.props; const oldValue = this.state.value; const newValue = e.target.value; const listValue = e.target.value.split(','); if (newValue.match(/,$/) && oldValue.match(/, $/)) { listValue.pop(); } const parsedValue = valueToString(listValue); this.setState({ value: parsedValue }); onChange(listValue.map(val => val.trim())); }; handleCleanup = (e) => { const listValue = e.target.value.split(',').map(el => el.trim()).filter(el => el); this.setState({ value: valueToString(listValue) }); }; handleAdd = (e) => { e.preventDefault(); const { value, onChange } = this.props; const parsedValue = (this.valueType === valueTypes.SINGLE) ? null : Map(); onChange((value || List()).push(parsedValue)); }; handleChangeFor(index) { return (newValue, newMetadata) => { const { value, metadata, onChange, forID } = this.props; const parsedValue = (this.valueType === valueTypes.SINGLE) ? newValue.first() : newValue; const parsedMetadata = { [forID]: Object.assign(metadata ? metadata.toJS() : {}, newMetadata ? newMetadata[forID] : {}), }; onChange(value.set(index, parsedValue), parsedMetadata); }; } handleRemove(index) { return (e) => { e.preventDefault(); const { value, metadata, onChange, forID } = this.props; const parsedMetadata = metadata && { [forID]: metadata.removeIn(value.get(index).valueSeq()) }; onChange(value.remove(index), parsedMetadata); }; } handleToggle(index) { return (e) => { e.preventDefault(); const { itemStates } = this.state; this.setState({ itemStates: itemStates.setIn([index, 'collapsed'], !itemStates.getIn([index, 'collapsed'])), }); }; } objectLabel(item) { const { field } = this.props; const multiFields = field.get('fields'); const singleField = field.get('field'); const labelField = (multiFields && multiFields.first()) || singleField; const value = multiFields ? item.get(multiFields.first().get('name')) : singleField.get('label'); return value || `No ${ labelField.get('name') }`; } handleSort = (obj) => { this.setState({ draggingIndex: obj.draggingIndex }); if ('items' in obj) { this.props.onChange(fromJS(obj.items)); } }; renderItem(item, index) { const { value, field, getAsset, onAddAsset, onRemoveAsset } = this.props; const { itemStates } = this.state; const collapsed = itemStates.getIn([index, 'collapsed']); const classNames = [styles.item, collapsed ? styles.collapsed : styles.expanded]; return (<SortableListItem key={index} updateState={this.handleSort} // eslint-disable-line items={value ? value.toJS() : []} draggingIndex={this.state.draggingIndex} sortId={index} outline="list" > <div className={classNames.join(' ')}> <button className={styles.toggleButton} onClick={this.handleToggle(index)}> <FontIcon value={collapsed ? 'expand_more' : 'expand_less'} /> </button> <FontIcon value="drag_handle" className={styles.dragIcon} /> <button className={styles.removeButton} onClick={this.handleRemove(index)}> <FontIcon value="close" /> </button> <div className={styles.objectLabel}>{this.objectLabel(item)}</div> <ObjectControl value={item} field={field} className={styles.objectControl} onChange={this.handleChangeFor(index)} getAsset={getAsset} onAddAsset={onAddAsset} onRemoveAsset={onRemoveAsset} /> </div> </SortableListItem>); } renderListControl() { const { value, forID, field } = this.props; const listLabel = field.get('label'); return (<div id={forID}> {value && value.map((item, index) => this.renderItem(item, index))} <button className={styles.addButton} onClick={this.handleAdd}> <FontIcon value="add" className={styles.addButtonIcon} /> <span className={styles.addButtonText}>new {listLabel}</span> </button> </div>); } render() { const { field, forID } = this.props; const { value } = this.state; if (field.get('field') || field.get('fields')) { return this.renderListControl(); } return (<input type="text" id={forID} value={value} onChange={this.handleChange} onBlur={this.handleCleanup} />); } }
weather-app/src/containers/weather_list.js
murielg/react-redux
import _ from 'lodash'; import React, { Component } from 'react'; import {connect} from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map'; class WeatherList extends Component { renderWeather (cityData) { const name = cityData.city.name; const strokeWidth = 0.25; const temps = _.map(cityData.list.map(weather => weather.main.temp), (temp) => _.round(_.subtract(_.multiply(temp,9/5), 459.67))); const pressures = cityData.list.map(weather => weather.main.pressure); const humidities = cityData.list.map(weather => weather.main.humidity); const { lon, lat } = cityData.city.coord; return ( <tr key={name} > <td><GoogleMap lon={lon} lat={lat} /></td> <td><Chart data={temps} type="temperature" colors={{strokeWidth:strokeWidth, stroke: "rgba(203, 75, 22,1)", fill: "rgba(203, 75, 22,0.5)" }} /></td> <td><Chart data={pressures} type="pressure" colors={{strokeWidth:strokeWidth, stroke: "rgba(38, 139, 210,1)", fill: "rgba(38, 139, 210,0.5)" }} /></td> <td><Chart data={humidities} type="humidity" colors={{strokeWidth:strokeWidth, stroke: "rgba(42, 161, 152,1)", fill: "rgba(42, 161, 152,0.5)" }} /></td> </tr> ); } render() { return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (F) </th> <th>Pressure (inHg) </th> <th>Humidity (%)</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } function mapStateToProps ({ weather }) { return { weather } // <= the same as => {weather : weather } } export default connect (mapStateToProps)(WeatherList);
frontend/src/components/BackupConfig/ConnHistory.js
XiaocongDong/mongodb-backup-manager
import React, { Component } from 'react'; import Draggable from 'components/Draggable'; import object from 'utility/object'; class HistoryHeader extends Draggable { render() { const ids = this.props.selectedIds; return ( <div className="history-connections-header" ref={ input => this.draggableDOM = input }> <div className={"select clickable" + (ids.length != 1? " disabled": "")} onClick={ this.props.selectConnection } > select </div> <div className={"delete clickable" + (ids.length == 0? " disabled": "")} onClick={ this.props.deleteConnections } > delete </div> <i className="fa fa-times close clickable" onClick={ this.props.onClickClose } aria-hidden={ true }></i> </div> ) } } const headConfig = [ { 'type': 'input', 'width': '5%' }, { 'type': 'text', 'key': 'server', 'text': 'DB Server', 'width': '50%' }, { 'type': 'text', 'key': 'username', 'text': 'user', 'width': '20%' }, { 'type': 'text', 'text': 'auth DB', 'key': 'authDB', 'width': '25%' } ]; export default class History extends Component { constructor(props) { super(props); this.state = { selectedIds: [] }; } setCredentials(backupConfig) { this.props.setCredentials(backupConfig); } toggleSingleId(id) { let selectedIds = object.clone(this.state.selectedIds); if(!selectedIds.includes(id)) { selectedIds.push(id); }else { selectedIds = selectedIds.filter(selectedId => selectedId != id); } this.setState({ selectedIds }); } toggleSelectAll(event) { const checked = event.target.checked; const connections = this.props.connections; let selectedIds = []; if(checked) { selectedIds = connections.map(conn => conn.id); } this.setState({ selectedIds }) } deleteConnections() { const selectedIds = this.state.selectedIds; if(selectedIds.length < 1) { return; } this.props.deleteConnections(selectedIds); } selectConnection() { const selectedIds = this.state.selectedIds; if(selectedIds.length != 1) { return; } const id = selectedIds[0]; const connection = object.filterArrWithKeyValue('id', id, this.props.connections)[0]; this.props.setCredentials(connection); } render() { const props = this.props; const connections = props.connections; const selectedIds = this.state.selectedIds; let headElements = headConfig.map((head, index) => { return ( <div className="td" key={ index } style={ { width: head.width } }> { (head.type == 'text')?head.text: (<input type="checkbox" onChange={ this.toggleSelectAll.bind(this) } />) } </div> ) }); headElements = <div className={"tr"}>{ headElements }</div>; let bodyElements = connections.map((conn, index) => { let connDOM = headConfig.map((head, i) => { return ( <div className="td" key={ i } style={ { width: head.width } }> { (head.type == 'text')? conn[head.key]: (<input type="checkbox" checked={ selectedIds.includes(conn.id) } />) } </div> ) }); connDOM = ( <div className={"tr clickable" + (selectedIds.includes(conn.id)?" selected": "") } key={ index } onClick={ this.toggleSingleId.bind(this, conn.id) } > { connDOM } </div> ) return connDOM; }); return ( <div className="history-connections" data-draggable={ true } > <div className="connections-table"> <HistoryHeader selectedIds= { selectedIds } onClickClose={ this.props.onClickClose } deleteConnections={ this.deleteConnections.bind(this) } selectConnection={ this.selectConnection.bind(this) } /> <div className="table"> <div className="thead"> { headElements } </div> <div className="tbody"> { bodyElements } </div> </div> </div> </div> ) } }
docs/app/Examples/collections/Form/Variations/FormExampleSize.js
aabustamante/Semantic-UI-React
import React from 'react' import { Button, Divider, Form } from 'semantic-ui-react' const sizes = ['mini', 'tiny', 'small', 'large', 'big', 'huge', 'massive'] const FormExampleSize = () => ( <div> {sizes.map(size => ( <Form size={size} key={size}> <Form.Group widths='equal'> <Form.Field label='First name' control='input' placeholder='First name' /> <Form.Field label='Last name' control='input' placeholder='Last name' /> </Form.Group> <Button type='submit'>Submit</Button> <Divider hidden /> </Form> ))} </div> ) export default FormExampleSize
src/js/components/InfiniteScroll/stories/HeightReplace.js
grommet/grommet
import React from 'react'; import { Box, InfiniteScroll, Text } from 'grommet'; const allItems = Array(240) .fill() .map((_, i) => i + 1); export const HeightReplace = () => ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <Box> <InfiniteScroll items={allItems} replace> {(item) => ( <Box key={item} height={item <= 25 ? 'xsmall' : 'xxsmall'} pad="medium" border={{ side: 'bottom' }} align="center" > <Text>item {item}</Text> </Box> )} </InfiniteScroll> </Box> // </Grommet> ); HeightReplace.storyName = 'Variable item height with replace'; HeightReplace.parameters = { chromatic: { disable: true }, }; export default { title: 'Utilities/InfiniteScroll/Variable item height with replace', };
example/src/screens/types/tabs/TabOne.js
junedomingo/react-native-navigation
import React from 'react'; import {View, Text} from 'react-native'; class TabOne extends React.Component { render() { return ( <View> <Text>Tab One</Text> </View> ); } } export default TabOne;
src/partials/announcement.js
getinsomnia/insomnia.rest
import React from 'react'; class Announcement extends React.Component { static defaultProps = { loggedIn: false, }; constructor(props) { super(props); this.state = { visible: false, }; } componentDidMount() { const { storageKey } = this.props; if (localStorage.getItem(`announcement.${storageKey}`) !== 'hide') { this.setState({ visible: true }); } } close(e) { e.preventDefault(); const { storageKey } = this.props; localStorage.setItem(`announcement.${storageKey}`, 'hide'); this.setState({ visible: false }); } render() { const { visible } = this.state; if (!visible) { return null; } return ( <div className="announcement"> <div className="container"> <div className="row"> <div className="col-12"> <a href="#" className="close-icon" onClick={this.close.bind(this)}> &times; </a> {this.props.children} </div> </div> </div> </div> ); } } export default Announcement;
admin/client/App/screens/Home/components/Section.js
danielmahon/keystone
import React from 'react'; import getRelatedIconClass from '../utils/getRelatedIconClass'; class Section extends React.Component { render () { const iconClass = this.props.icon || getRelatedIconClass(this.props.id); return ( <div className="dashboard-group" data-section-label={this.props.label}> <div className="dashboard-group__heading"> <span className={`dashboard-group__heading-icon ${iconClass}`} /> {this.props.label} </div> {this.props.children} </div> ); } } Section.propTypes = { children: React.PropTypes.element.isRequired, icon: React.PropTypes.string, id: React.PropTypes.string, label: React.PropTypes.string.isRequired, }; export default Section;
babel-plugin-css-in-js/button.js
MicheleBertoli/css-in-js
import React from 'react'; import { render } from 'react-dom'; const styles = cssInJS({ container: { textAlign: 'center' }, button: { backgroundColor: '#ff0000', width: 320, padding: 20, borderRadius: 5, border: 'none', outline: 'none', ':hover': { color: '#fff' }, ':active': { position: 'relative', top: 2 }, '@media (max-width: 480px)': { width: 160 } } }); class Button extends React.Component { render() { return ( <div className={styles.container}> <button className={styles.button}>Click me!</button> </div> ); } } render(<Button />, document.getElementById('content'));
src/pages/about.js
dkonieczek/dkonieczek.github.io
import React from 'react'; import Link from 'gatsby-link'; import frontend from '../assets/frontend.png'; import backend from '../assets/backend.png'; import tools from '../assets/tools.png'; import creative from '../assets/creative.png'; import design from '../assets/design.png'; const AboutPage = () => ( <div className="about"> <h2>About Me</h2> <p className="bio"> Hey there! My name is Dennis Konieczek, I am a full stack web developer based in Toronto, Canada. I love all things tech, however I’ve focused my career on web development. I am familiar with a wide variety of skills and have worked on multiple exciting projects which you can check out here on my personal website. </p> <h3>Experience</h3> <ul> <li> <p className="date">07/2016 - Present</p> <p> Technical Support &amp; Software Developer <span> Tools: HTML, CSS, JavaScript, NodeJS, jQuery, PHP <br /> <br /> Developed solutions for integrating onboarding clients from ecommerce platforms such as Magento, Volusion, Bigcommerce, Yahoo, Shopify, 3DCart and NetSuite. <br /> <br /> Developed automated end to end test cases. <br /> <br /> Provided technical email &amp; phone support. <br /> <br /> Participated and provide opinion in daily standups and weekly sprint meetings as part of the scrum agile methodology. </span> </p> </li> <li> <p className="date">07/2014 - 07/2015</p> <p> Technical Support Specialist <span> Provided hardware, application and network specific support. <br /> <br /> Managed physical hardware assets <br /> <br /> Deployment of Cisco VoIP hardware </span> </p> </li> </ul> <h3>Skills</h3> <div className="skills"> <div className="skill"> <img src={frontend} /> <p className="heading">Front End</p> <p className="desc"> HTML5, CSS grid, Flexbox, SASS, Javascript (ES5/ES6), jQuery, React.js </p> </div> <div className="skill"> <img src={backend} /> <p className="heading">Back End</p> <p className="desc">Node, Express, MongoDB, PHP</p> </div> <div className="skill"> <img src={tools} /> <p className="heading">Tools</p> <p className="desc">Npm, Git, Webpack</p> </div> <div className="skill"> <img src={creative} /> <p className="heading">Creative Direction</p> <p className="desc"> Agile/Scrum methodologies, effective communication </p> </div> <div className="skill"> <img src={design} /> <p className="heading">Design</p> <p className="desc"> Responsive design, Accessibility, W3C Standards, Photoshop, Illustrator </p> </div> </div> </div> ); export default AboutPage;
client/modules/users/components/bye.js
freiraumpetersburg/mitgliederverwaltung
import {Meteor} from 'meteor/meteor'; import React from 'react'; class Bye extends React.Component { componentWillMount() { Meteor.logout(); } render() { return ( <div> <h2>Bye</h2> <p>Hope to see you soon!</p> </div> ); } } export default Bye;
examples/todos/src/index.js
gaearon/redux
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import App from './components/App' import rootReducer from './reducers' const store = createStore(rootReducer) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
client/react/src/components/common/Header.js
peasy/peasy-js-samples
import React from 'react'; import { NavLink } from 'react-router-dom'; import constants from '../../constants'; let routes = constants.routes; const Header = () => { return ( <nav className="navbar navbar-expand-lg navbar-dark bg-dark"> <ul className="navbar-nav mr-auto"> <li className="nav-item"> <NavLink to={routes.ORDERS} className="nav-link" activeClassName="active">Orders</NavLink> </li> <li className="nav-item"> <NavLink to={ routes.CUSTOMERS } className="nav-link" activeClassName="active">Customers</NavLink> </li> <li className="nav-item"> <NavLink to={ routes.CATEGORIES } className="nav-link" activeClassName="active">Categories</NavLink> </li> <li className="nav-item"> <NavLink to={ routes.PRODUCTS } className="nav-link" activeClassName="active">Products</NavLink> </li> <li className="nav-item"> <NavLink to={ routes.INVENTORY_ITEMS } className="nav-link" activeClassName="active">Inventory</NavLink> </li> </ul> </nav> ); }; export default Header;
packages/mineral-ui-icons/src/IconWifiTethering.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconWifiTethering(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M12 11c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 2c0-3.31-2.69-6-6-6s-6 2.69-6 6c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-2.21 1.79-4 4-4s4 1.79 4 4c0 1.48-.81 2.75-2 3.45l1 1.74c1.79-1.04 3-2.97 3-5.19zM12 3C6.48 3 2 7.48 2 13c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 18.53 4 15.96 4 13c0-4.42 3.58-8 8-8s8 3.58 8 8c0 2.96-1.61 5.53-4 6.92l1 1.73c2.99-1.73 5-4.95 5-8.65 0-5.52-4.48-10-10-10z"/> </g> </Icon> ); } IconWifiTethering.displayName = 'IconWifiTethering'; IconWifiTethering.category = 'device';
boilerplates/project/pcWeb/src/components/App/App.js
FuluUE/vd-generator
import React from 'react'; import PropTypes from 'prop-types'; class App extends React.Component { static defaultProps = {} static propTypes = {} constructor(props) { super(props); } render() { return 'Hello World!' } } export default App;
src/svg-icons/device/battery-charging-60.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging60 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/> </SvgIcon> ); DeviceBatteryCharging60 = pure(DeviceBatteryCharging60); DeviceBatteryCharging60.displayName = 'DeviceBatteryCharging60'; DeviceBatteryCharging60.muiName = 'SvgIcon'; export default DeviceBatteryCharging60;
frontend/src/Map.js
googleinterns/step238-2020
import React, { Component } from 'react'; import ITINERARY_KEY from "./configMap"; import WEATHER_KEY from "./configWeather"; import './Itinerary.css'; import Button from "react-bootstrap/Button"; class Map extends Component { constructor(props) { super(props); this.onScriptLoad = this.onScriptLoad.bind(this); this.getSavedItinerary = this.getSavedItinerary.bind(this); this.saveUserItinerary = this.saveUserItinerary.bind(this); this.callLoad = this.callLoad.bind(this); this.generateRouteDirections = this.generateRouteDirections.bind(this); } onScriptLoad() { const map = new window.google.maps.Map( document.getElementById(this.props.id), this.props.options); let query = localStorage["url"]; let vars = query.split("&"); let query_string = {}; for (let i = 0; i < vars.length; i++) { const pair = vars[i].split("="); const key = decodeURIComponent(pair[0]); const value = decodeURIComponent(pair[1]); query_string[key] = value; } let urlParameters = query_string; const directionsService = new window.google.maps.DirectionsService(); const directionsRenderer = new window.google.maps.DirectionsRenderer(); directionsRenderer.setMap(map); let waypts = []; query = localStorage["url"]; vars = query.split("&"); query_string = {}; for (var i = 0; i < vars.length; i++) { const pair = vars[i].split("="); const key = decodeURIComponent(pair[0]); const value = decodeURIComponent(pair[1]); query_string[key] = value; } urlParameters = query_string; const locations = urlParameters.locations.split('*'); const start = locations[0]; const finish = locations[locations.length - 1]; for (let i = 1; i < locations.length - 1; i++) { waypts.push({ location: locations[i], stopover: true, }); } if (localStorage["date"] !== undefined) { const datetime = localStorage["date"]; const lat = start.split(',')[0]; const long = start.split(',')[1]; const key = Object.values(WEATHER_KEY)[0]; // Create the API url for starting point. let urlWeather = 'https://api.openweathermap.org/data/2.5/onecall?lat='; urlWeather += lat; urlWeather += '&lon='; urlWeather += long; urlWeather += '&exclude=current,minutely,hourly&appid='; urlWeather += key; // Call the API for 8 days weather forecast. fetch(urlWeather) .then(response => response.json()) .then(function(response) { let weatherDiv = document.getElementById('weather'); response = response.daily; // Find the correct datetime range for date parameter that came from landing page. for (let i = 0; i < response.length - 1; i++) { if (response[i].dt <= datetime && datetime <= response[i + 1].dt) { // Show the correct day's weather forecast. weatherDiv.innerHTML = "Weather forecast: "; weatherDiv.innerHTML += Math.floor(response[i].temp.day - 273.15); weatherDiv.innerHTML += "°C " + response[i].weather[0].main; break; } } }); } let delayFactor = 0; let request = { origin: start, destination: finish, waypoints: waypts, optimizeWaypoints: true, travelMode: window.google.maps.TravelMode.DRIVING }; this.generateRouteDirections(delayFactor, request, directionsRenderer, directionsService); this.props.onMapLoad(map) } generateRouteDirections(delayFactor, request, directionsRenderer, directionsService) { directionsService.route( request, (response, status) => { if (status === 'OK') { directionsRenderer.setDirections(response); const route = response.routes[0]; const summaryPanel = document.getElementById('directions-panel'); summaryPanel.innerHTML = ''; let directionsData = response.routes[0].legs[0]; let durationTotal = 0.0, distanceTotal = 0.0; for (let i = 0; i < route.legs.length; i++) { const routeSegment = i + 1; summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>'; summaryPanel.innerHTML += route.legs[i].start_address + ' to '; summaryPanel.innerHTML += route.legs[i].end_address + '<br>'; summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>'; distanceTotal += Math.round(parseFloat(directionsData.distance.text)); durationTotal += Math.round(parseFloat(directionsData.duration.text)); } document.getElementById('duration').innerHTML = " Total distance is " + distanceTotal + " km and the total time is " + durationTotal + " min"; } else if (status === window.google.maps.DirectionsStatus.OVER_QUERY_LIMIT) { delayFactor++; setTimeout(function() { this.m_get_directions_route(); }, delayFactor * 1000); } else { window.alert('Directions request failed due to ' + status); } }, ) }; componentDidMount() { if (!window.google) { const key = Object.values(ITINERARY_KEY)[0]; var s = document.createElement('script'); s.type = 'text/javascript'; s.src = `https://maps.google.com/maps/api/js?key=` + key; document.head.appendChild(s); s.addEventListener('load', e => { this.onScriptLoad() }) } else { this.onScriptLoad(); } } saveUserItinerary() { const params = new URLSearchParams(); params.append('userID', localStorage["id"]); params.append('tripID', localStorage["url"]); params.append('tripName', localStorage["searchValue"]); fetch('/api/database', { method: 'POST', body: params }).then((response) => response.json()) .then((text) => { document.getElementById("save").innerText = text; if (text === "trip already saved") document.getElementById("save").style.backgroundColor = "red"; else document.getElementById("save").style.backgroundColor = "green"; }); } getSavedItinerary() { fetch(`/api/database?userID=${localStorage["id"]}`, { method: 'GET' }).then((response) => response.json()) .then((trips) => { // we get the buttons location let buttonLocation = document.getElementById("saved"); // delete all the previous buttons buttonLocation.innerHTML = "<h4>Previous created trips</h4> <br/> <br/>"; //we create the buttons for (let i = 0; i < trips.length; i++) { const button = document.createElement("button"); button.innerText = trips[i].tripName; button.style.backgroundColor = "cadetblue"; button.style.color = "aliceblue"; let currentUrl = trips[i].tripID === undefined ? 'locations=' : trips[i].tripID; button.id = trips[i].id; button.addEventListener("click", e => { this.callLoad(currentUrl) }) buttonLocation.appendChild(button); //we add the delete button const buttondel = document.createElement("button"); buttondel.innerText = "remove trip"; buttondel.id = trips[i].timestamp; buttondel.addEventListener("click", function() { //we first delete the button with the url const params = new URLSearchParams(); params.append("id", trips[i].id); fetch( 'api/delete', { method: 'post', body: params }) document.getElementById(trips[i].id).remove(); document.getElementById(trips[i].timestamp).remove(); //then we delete it from the database }); buttonLocation.appendChild(buttondel); } }) } callLoad(currentUrl) { localStorage.setItem("url", currentUrl); this.onScriptLoad(); } render() { return ( <div> <div id="left-panel"> <div id="weather"></div> <div id="directions-panel"></div> <br /> <br /> <br /> <div id="saved"></div> </div> <h1 id="title">My Itinerary</h1> <div class="mapbtn"> <Button id='save' onClick={this.saveUserItinerary}>Save this itinerary</Button> <Button id='prev' onClick={this.getSavedItinerary} href="#saved">Previous trips</Button> <div id="duration"> </div> </div> <div style={{ width: 1000, height: 800, float: 'left', position: 'absolute', left: '35%' }} id={this.props.id}></div> </div> ); } } export default Map;
expense-manager-app/src/routers/AppRouter.js
VeeShostak/Expense-Manager
import React from 'react'; import {Router, Route, Switch, Link, NavLink} from 'react-router-dom'; import createHistory from 'history/createBrowserHistory'; import ExpenseDashboardPage from '../components/ExpenseDashboardPage'; import AddExpensePage from '../components/AddExpensePage'; import EditExpensePage from '../components/EditExpensePage'; import NotFoundPage from '../components/NotFoundPage'; import Header from '../components/Header'; import LoginPage from '../components/LoginPage' import PrivateRoute from './PrivateRoute'; // used as a "wrapper" around Route import PublicRoute from './PublicRoute'; // used as a "wrapper" around Route export const history = createHistory(); // sfc component const AppRouter = () => ( <Router history={history}> <div> {/* Switch: if found match stop */} <Switch> <PublicRoute path="/" component={LoginPage} exact={true}/> <PrivateRoute path="/dashboard" component={ExpenseDashboardPage}/> <PrivateRoute path="/create" component={AddExpensePage}/> <PrivateRoute path="/edit/:id" component={EditExpensePage}/> <Route component={NotFoundPage} /> </Switch> </div> </Router> ); export default AppRouter;
webpack/scenes/Subscriptions/Manifest/DeleteManifestModalText.js
johnpmitsch/katello
import React from 'react'; import { translate as __ } from 'foremanReact/common/I18n'; const question = __('Are you sure you want to delete the manifest?'); const note = __(`Note: Deleting a subscription manifest is STRONGLY discouraged. Deleting a manifest will:`); const l1 = __('Delete all subscriptions that are attached to running hosts.'); const l2 = __('Delete all subscriptions attached to activation keys.'); const l3 = __('Disable Red Hat Insights.'); const l4 = __(`Require you to upload the subscription-manifest and re-attach subscriptions to hosts and activation keys.`); const debug = __(`This action should only be taken in extreme circumstances or for debugging purposes.`); const DeleteManifestModalText = () => ( <React.Fragment> <p>{question}</p> <p>{note}</p> <ul className="list-aligned"> <li>{l1}</li> <li>{l2}</li> <li>{l3}</li> <li>{l4}</li> </ul> <p>{debug}</p> </React.Fragment> ); export default DeleteManifestModalText;
src/containers/home-container.js
ChrisRast/Le-Taguenet
import React from 'react'; import * as r from 'react-router-dom'; import * as ui from 'semantic-ui-react'; import { ROUTES } from '../config/routes'; export default class Home extends React.PureComponent { render () { return ( <ui.Container text > <ui.Header> Bienvenus sur Le Taguenet ! </ui.Header> <p> Ce site a été dévelopé pour vous permettre de compléter le texte lacunaire homonyme à l'ère du numérique. </p> <p> Pour essayer de trouver tous les mots, rendez-vous sur la page <r.Link to={ROUTES['text'].path}>Le texte</r.Link>. </p> <p> C'est également un exercice personnel d'expérimentation de différentes technologies de dévelopment web&nbsp; <a href="https://fr.wikipedia.org/wiki/D%C3%A9veloppement_web_frontal" target="_blank" rel="noopener external nofollow noreferrer" > front-end </a> utilisant les librairies&nbsp; <a href="https://reactjs.org/" target="_blank" rel="noopener external nofollow noreferrer" > React </a>, <a href="https://reacttraining.com/react-router/" target="_blank" rel="noopener external nofollow noreferrer" > React-Router </a> et&nbsp; <a href="https://semantic-ui.com/" target="_blank" rel="noopener external nofollow noreferrer" > Semantic-UI </a> . </p> </ui.Container> ); } }
app/components/GeneratedKeysView.js
ixje/neon-wallet-react-native
import React from 'react' import { ScrollView, View, Text, StyleSheet, TextInput, Clipboard } from 'react-native' import KeyDataRow from './KeyDataRow' import Button from './Button' import { DropDownHolder } from '../utils/DropDownHolder' import PropTypes from 'prop-types' class GeneratedKeysView extends React.Component { constructor(props) { super(props) this.dropdown = DropDownHolder.getDropDown() this.state = { saveDisabled: true, saved: false } } _saveKey() { this.props.saveKeyCallback(this.txtKeyName._lastNativeText) this.txtKeyName.blur() this.setState({ saved: true }) } _txtKeyNameChanged(text) { text.length > 0 ? this.setState({ saveDisabled: false }) : this.setState({ saveDisabled: true }) } _renderStoreOnDevice() { if (!this.state.saved) { return ( <View> <View style={styles.spacer} /> <Text style={[styles.instructionText, { textAlign: 'left', marginLeft: 20 }]}>Store on device</Text> <TextInput ref={txtInput => { this.txtKeyName = txtInput }} multiline={false} placeholder="Name this key" placeholderTextColor="#636363" returnKeyType="done" style={styles.inputBox} autoCorrect={false} onChangeText={this._txtKeyNameChanged.bind(this)} /> {this.state.saveDisabled ? null : <Button onPress={this._saveKey.bind(this)} title="Save key" />} <View style={{ height: 10, backgroundColor: 'white' }} /> </View> ) } else { return ( <View> <View style={styles.spacer} /> <Text style={[styles.instructionText, { marginTop: 20 }]}>Key "{this.txtKeyName._lastNativeText}" saved!</Text> </View> ) } } _copyToClipBoard() { const { passphrase, address, encryptedWIF, wif } = this.props const data = { passphrase: passphrase, public_address: address, encrypted_key: encryptedWIF, private_key: wif } Clipboard.setString(JSON.stringify(data)) this.dropdown.alertWithType('info', 'Success', 'Data copied to clipboard. Be careful where you paste the data!') } render() { const { passphrase, address, encryptedWIF, wif } = this.props return ( <ScrollView> <View style={styles.warningView}> <Text style={styles.warningText}> You must save and backup the keys below. If you lose them, you lose access to your assets. You can click "Save Key" to save the encrypted key on your mobile device. Note that a rooted or jailbroken phone can pose a risk to your keys. Verify that you can log in to the account and see the correct public address before sending anything to the address below! </Text> </View> <View style={styles.dataList}> <KeyDataRow title="Passphrase" value={passphrase} /> <KeyDataRow title="Public address" value={address} /> <KeyDataRow title="Encrypted key" value={encryptedWIF} /> <KeyDataRow title="Private key" value={wif} /> </View> <Button onPress={this._copyToClipBoard.bind(this)} title="Copy data to clipboard" /> <Button onPress={() => { alert('Not functional yet') }} title="Email data" /> {this._renderStoreOnDevice()} </ScrollView> ) } } GeneratedKeysView.propTypes = { saveKeyCallback: PropTypes.func, wif: PropTypes.string, passphrase: PropTypes.string, encryptedWIF: PropTypes.string, address: PropTypes.string } const styles = StyleSheet.create({ warningView: { flexDirection: 'row', backgroundColor: 'red' }, warningText: { marginHorizontal: 20, paddingVertical: 5, color: 'white' }, dataList: { flexDirection: 'column', justifyContent: 'flex-start' // vertical }, spacer: { height: 2, backgroundColor: '#EFEFEF', marginHorizontal: 30, marginVertical: 20 }, inputBox: { marginHorizontal: 20, marginVertical: 5, paddingLeft: 10, // paddingTop: 5, height: 36, fontSize: 14, backgroundColor: '#E8F4E5', color: '#333333' }, instructionText: { color: '#333333', fontSize: 14, textAlign: 'center', marginBottom: 10 } }) export default GeneratedKeysView
src/settings/OwnerSettings.js
folio-org/ui-users
import _ from 'lodash'; import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage, } from 'react-intl'; import { Field } from 'react-final-form'; import { MultiSelection, Label, } from '@folio/stripes/components'; import { ControlledVocab } from '@folio/stripes/smart-components'; import { stripesConnect, withStripes } from '@folio/stripes/core'; import { validate } from '../components/util'; const columnMapping = { owner: ( <Label tagName="span" required > <FormattedMessage id="ui-users.owners.columns.owner" /> </Label> ), desc: <FormattedMessage id="ui-users.owners.columns.desc" />, servicePointOwner: ( <Label id="associated-service-point-label"> <FormattedMessage id="ui-users.owners.columns.asp" /> </Label> ), }; class OwnerSettings extends React.Component { static manifest = Object.freeze({ ownerServicePoints: { type: 'okapi', resource: 'service-points', path: 'service-points?limit=200', }, owners: { type: 'okapi', records: 'owners', path: 'owners', GET: { path: 'owners?query=cql.allRecords=1 sortby owner&limit=2000' } }, }); static propTypes = { stripes: PropTypes.shape({ connect: PropTypes.func.isRequired, }).isRequired, resources: PropTypes.object, intl: PropTypes.object.isRequired, }; constructor(props) { super(props); this.connectedControlledVocab = props.stripes.connect(ControlledVocab); } validateItem = (item, index, items) => { const { intl: { formatMessage } } = this.props; const label = formatMessage({ id: 'ui-users.owners.singular' }); const itemErrors = validate(item, index, items, 'owner', label); const evaluateServicePoint = item.servicePointOwner ? item.servicePointOwner.length : 0; if (item.owner === 'Shared' && evaluateServicePoint > 0) { itemErrors.owner = formatMessage({ id: 'ui-users.owners.noServicePoints' }); } return itemErrors; } warn = ({ items }) => { const servicePoints = _.get(this.props.resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []); const none = servicePoints.find(s => s.name === 'None') || {}; const warnings = []; if (Array.isArray(items)) { items.forEach((item, index) => { const itemWarning = {}; const asp = item.servicePointOwner || []; asp.forEach(s => { if (s.value === none.id) { itemWarning.servicePointOwner = <FormattedMessage id="ui-users.owners.warning" />; } }); if (Object.keys(itemWarning).length) { warnings[index] = itemWarning; } }); } return { items: warnings }; } render() { const { intl: { formatMessage }, resources } = this.props; const label = formatMessage({ id: 'ui-users.owners.singular' }); const rows = _.get(resources, ['owners', 'records'], []); const servicePoints = _.get(resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []); const serviceOwners = []; rows.forEach(o => { const asp = o.servicePointOwner || []; asp.forEach(s => { if (!serviceOwners.includes(s.value)) { serviceOwners.push(s.value); } }); }); const options = []; servicePoints.forEach(s => { if (!serviceOwners.includes(s.id) || s.name === 'None') { options.push({ value: s.id, label: s.name }); } }); const fieldComponents = { 'servicePointOwner': ({ fieldProps }) => ( <Field {...fieldProps} id="owner-service-point" component={MultiSelection} aria-labelledby="associated-service-point-label" dataOptions={options} renderToOverlay marginBottom0 validationEnabled onBlur={e => e.preventDefault()} /> ) }; const formatter = { 'servicePointOwner': (value) => { const asp = value.servicePointOwner || []; const items = asp.map(a => <li key={a.label}>{a.label}</li>); return <ul>{items}</ul>; } }; return ( <this.connectedControlledVocab {...this.props} baseUrl="owners" columnMapping={columnMapping} fieldComponents={fieldComponents} formatter={formatter} hiddenFields={['lastUpdated', 'numberOfObjects']} id="settings-owners" label={formatMessage({ id: 'ui-users.owners.label' })} labelSingular={label} nameKey="owner" objectLabel="" records="owners" sortby="owner" validate={this.validateItem} visibleFields={['owner', 'desc', 'servicePointOwner']} warn={this.warn} formType="final-form" /> ); } } export default injectIntl(withStripes(stripesConnect(OwnerSettings)));
src/components/layout/Sidebar.js
huang6349/react-dva
import React, { Component } from 'react'; import { Icon, Menu, } from 'antd'; import PropTypes from 'prop-types'; import { Link } from 'dva/router'; import { isEqual, isEmpty, last, uniq, filter, difference } from 'underscore'; import { MENU } from '../../utils/constants'; import styles from './Sidebar.css'; class Sidebar extends React.Component { static propTypes = { menus: PropTypes.array.isRequired, inlineCollapsed: PropTypes.bool.isRequired, pathname: PropTypes.string.isRequired, } state = { menus: [], selectedKeys: [], openKeys: [], } PREFIX_SUB = 'sub'; PREFIX_ITEM = 'item'; inlineCollapsed; inlineOpenKeys = []; current_name; parent_name; child_name; title_name; icon_name; url_name; pid; constructor(props) { super(props); this.inlineCollapsed = this.props.inlineCollapsed; this.current_name = MENU.ID; this.parent_name = MENU.PARENT_ID; this.child_name = MENU.CHILD; this.title_name = MENU.NAME; this.icon_name = MENU.ICON; this.url_name = MENU.URL; this.pid = MENU.PID; } componentWillMount() { // 导航菜单[设置默认展开项和选中项] this.setDefaultKeys(this.props.menus); } componentWillReceiveProps(nextProps) { if (nextProps.inlineCollapsed && !this.props.inlineCollapsed) { // 导航菜单[关闭] this.inlineOpenKeys = this.state.openKeys; this.setOpenKeys([]); } if (!nextProps.inlineCollapsed && this.props.inlineCollapsed) { // 导航菜单[展开] this.setOpenKeys(this.inlineOpenKeys); this.inlineOpenKeys = []; } if (!isEqual(this.props.menus, nextProps.menus)) { // 导航菜单[设置默认展开项和选中项] this.setDefaultKeys(nextProps.menus); } // 导航菜单[设置序列化导航菜单项的数据] this.setMenus(nextProps.menus); } setMenus(menus) { // 设置序列化导航菜单项的数据 this.setState({ menus: this.transformMenusData(menus) }); } setOpenKeys(openKeys) { // 设置导航菜单展开项 this.setState({ openKeys: openKeys }); } setSelectedKeys(selectedKeys) { // 设置导航菜单选中项 this.setState({ selectedKeys: selectedKeys }); } setDefaultKeys(items = []) { // 导航菜单[设置默认展开项和选中项] // 申明返回值 let selectedKeys = [], openKeys = []; // 获得选中菜单项 Array.from(items).forEach((value, index, array) => { if (isEqual(`${value[this.url_name]}`, this.props.pathname)) { selectedKeys = selectedKeys.concat(`${this.PREFIX_ITEM}-${value[this.current_name]}`); } }); // 获得打开菜单项 Array.from(selectedKeys).forEach((value, index, array) => { openKeys = openKeys.concat(this.getAncestorKeys(items, value)); }); // 更新值 this.setOpenKeys(openKeys); this.setSelectedKeys(uniq(selectedKeys)); } getAncestorKeys(items = [], id) { // 导航菜单[获得展开当前项需要的KEY值] // 申明返回值 let openKeys = []; // 获得父级打开菜单项 Array.from(items).forEach((value, index, array) => { if (value[this.parent_name] && isEqual(`${this.PREFIX_ITEM}-${value[this.current_name]}`, `${id}`)) { // 将当前项的父级菜单KEY值加入到展开项中 openKeys = openKeys.concat(`${this.PREFIX_SUB}-${value[this.parent_name]}`); // 递归计算当前项的祖级菜单KEY值,并加入到展开项中 openKeys = openKeys.concat(this.getAncestorKeys(items, `${this.PREFIX_ITEM}-${value[this.parent_name]}`)); } }); // 返回值 return uniq(openKeys); } getRootOpenKey(openKeys) { // 导航菜单[获得展开项的根级菜单项的KEY值] const keys1 = openKeys || []; const keys2 = this.state.openKeys || []; // 返回值 return keys1.length > keys2.length ? difference(keys1, keys2)[0] : difference(keys2, keys1)[0]; } handleChange(openKeys) { if (!isEqual(this.inlineCollapsed, this.props.inlineCollapsed)) { // 导航菜单[收起或展开状态发生变化后不执行更新KEY值的操作] this.inlineCollapsed = this.props.inlineCollapsed; return false; } // 导航菜单[展开项发生变化,更新导航菜单展开项的KEY值] // 初始化配置 const latestOpenKeys = openKeys; const latestCloseKeys = this.state.openKeys; // 获得展开项的根级菜单项的KEY值 const rootOpenKey = this.getRootOpenKey(latestOpenKeys); // 申明返回值 let nextOpenKeys = []; Array.from(this.props.menus || []).forEach((value, index, array) => { if (isEqual(`${this.PREFIX_SUB}-${value[this.current_name]}`, rootOpenKey)) { nextOpenKeys = this.getAncestorKeys(array, `${this.PREFIX_ITEM}-${value[this.current_name]}`); if (latestOpenKeys.length > latestCloseKeys.length) { nextOpenKeys = nextOpenKeys.concat(rootOpenKey); } } }); // 更新值 this.setOpenKeys(uniq(nextOpenKeys)); } handleClick({ item, key, keyPath }) { // 导航菜单[选中项发生变化,更新导航菜单选中项的KEY值] this.setSelectedKeys([key]); } transformMenusData(items = [], config = {}) { // 数据转换[将类树形结构的数据转换为树形结构的数据] // 初始化配置 const pid = config.pid || this.pid; // 申明返回值 let menus = []; // 构造树形结构数据 Array.from(items).forEach((item, index, array) => { if (isEqual(`${item[this.parent_name]}`, `${pid}`)) { let menu = Object.assign([], item); menu[this.child_name] = Object.assign([], this.transformMenusData(items, Object.assign(config, { pid: item[this.current_name] }))); menus.push(menu); } }); // 返回值 return menus; } serializeMenus(items = []) { // 数据序列化[将树形结构的菜单数据序列化为菜单项] // 序列化菜单项 return Array.from(items).map((item, index, array) => { const title = item[this.icon_name] ? <span><Icon type={item[this.icon_name]} /><span>{item[this.title_name]}</span></span> : item[this.title_name]; if (item[this.child_name] && item[this.child_name].length > 0) { return ( <Menu.SubMenu key={`${this.PREFIX_SUB}-${item[this.current_name]}`} title={title}> {this.serializeMenus(item[this.child_name])} </Menu.SubMenu> ); } else { return ( <Menu.Item key={`${this.PREFIX_ITEM}-${item[this.current_name]}`}> <Link to={item[this.url_name]}>{title}</Link> </Menu.Item> ); } }); } render() { return ( <Menu theme="dark" mode="inline" selectedKeys={this.state.selectedKeys} openKeys={this.state.openKeys} onOpenChange={this.handleChange.bind(this)} onClick={this.handleClick.bind(this)} multiple={false} inlineCollapsed={this.props.inlineCollapsed}> {this.serializeMenus.bind(this)(this.state.menus)} </Menu> ); } } export default Sidebar;
examples/shared-root/app.js
whouses/react-router
import React from 'react'; import { Router, Route, Link } from 'react-router'; var App = React.createClass({ render() { return ( <div> <p> This illustrates how routes can share UI w/o sharing the URL. When routes have no path, they never match themselves but their children can, allowing "/signin" and "/forgot-password" to both be render in the <code>SignedOut</code> component. </p> <ol> <li><Link to="/home">Home</Link></li> <li><Link to="/signin">Sign in</Link></li> <li><Link to="/forgot-password">Forgot Password</Link></li> </ol> {this.props.children} </div> ); } }); var SignedIn = React.createClass({ render() { return ( <div> <h2>Signed In</h2> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return ( <h3>Welcome home!</h3> ); } }); var SignedOut = React.createClass({ render() { return ( <div> <h2>Signed Out</h2> {this.props.children} </div> ); } }); var SignIn = React.createClass({ render() { return ( <h3>Please sign in.</h3> ); } }); var ForgotPassword = React.createClass({ render() { return ( <h3>Forgot your password?</h3> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route component={SignedOut}> <Route path="signin" component={SignIn} /> <Route path="forgot-password" component={ForgotPassword} /> </Route> <Route component={SignedIn}> <Route path="home" component={Home} /> </Route> </Route> </Router> ), document.getElementById('example'));
src/client/devtools.js
apazzolini/rook
import React from 'react'; import { compose as _compose, applyMiddleware } from 'redux'; import { createDevTools, persistState } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export const DevTools = createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor /> </DockMonitor> ); export const InvisibleDevTools = createDevTools( <DockMonitor defaultIsVisible={false} toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor /> </DockMonitor> ); export function compose(middleware) { const Tools = __DEVTOOLS_IS_VISIBLE__ ? DevTools : InvisibleDevTools; return _compose( applyMiddleware(...middleware), window.devToolsExtension ? window.devToolsExtension() : Tools.instrument(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) ); } // context: https://github.com/rackt/react-router-redux/compare/1.0.2...2.0.2 // context: https://github.com/rackt/react-router-redux/pull/141#issuecomment-167587581 export function listenToRouter(routerMiddleware, store) { routerMiddleware.listenForReplays(store); } export function render() { if (__DEVTOOLS__ && !window.devToolsExtension) { const Tools = __DEVTOOLS_IS_VISIBLE__ ? DevTools : InvisibleDevTools; return <Tools />; } }
src/components/Board/Output/SymbolOutput/BackspaceButton/BackspaceButton.js
shayc/cboard
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import BackspaceIcon from '@material-ui/icons/Backspace'; import { Scannable } from 'react-scannable'; const styles = { button: { alignSelf: 'center', height: '64px', width: '64px' }, icon: { height: '32px', width: '32px' } }; export class BackspaceButton extends Component { static propTypes = { /** * @ignore */ classes: PropTypes.object, /** * @ignore */ theme: PropTypes.object, hidden: PropTypes.bool }; render() { const { classes, theme, hidden, ...other } = this.props; const backspaceIconStyle = theme.direction === 'ltr' ? null : { transform: 'scaleX(-1)' }; return ( <Scannable disabled={hidden}> <IconButton aria-label="Backspace" className={classes.button} {...other} > <BackspaceIcon className={classes.icon} style={backspaceIconStyle} /> </IconButton> </Scannable> ); } } export default withStyles(styles, { withTheme: true })(BackspaceButton);
src/svg-icons/image/filter-6.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter6 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V7h4V5h-4c-1.1 0-2 .89-2 2v6c0 1.11.9 2 2 2zm0-4h2v2h-2v-2z"/> </SvgIcon> ); ImageFilter6 = pure(ImageFilter6); ImageFilter6.displayName = 'ImageFilter6'; ImageFilter6.muiName = 'SvgIcon'; export default ImageFilter6;
src/lens/negative-space/LensBottom.js
ethanselzer/react-image-magnify
import React from 'react'; import objectAssign from 'object-assign'; import clamp from 'clamp'; import Lens from './Lens'; import LensPropTypes from '../../prop-types/Lens'; const LensBottom = ({ cursorOffset, position, fadeDurationInMs, isActive, isPositionOutside, smallImage, style: parentSpecifiedStyle }) => { const clearLensHeight = cursorOffset.y * 2; const computedHeight = smallImage.height - position.y - cursorOffset.y; const maxHeight = smallImage.height - clearLensHeight; const height = clamp(computedHeight, 0, maxHeight); const clearLensBottom = position.y + cursorOffset.y; const top = Math.max(clearLensBottom, clearLensHeight); const computedStyle = { height: `${height}px`, width: '100%', top: `${top}px` }; return ( <Lens {...{ fadeDurationInMs, isActive, isPositionOutside, style: objectAssign( {}, parentSpecifiedStyle, computedStyle ) }}/> ); }; LensBottom.propTypes = LensPropTypes; export default LensBottom;
app/containers/HomePage.js
andrewjong/react-interactive-calculator
// @flow import React, { Component } from 'react'; import Home from '../components/Home'; export default class HomePage extends Component { render() { return ( <Home /> ); } }
src/browser/intl/SwitchLocale.js
sikhote/davidsinclair
// @flow import type { State } from '../../common/types'; import React from 'react'; import { Box, Button } from '../../common/components'; import { compose } from 'ramda'; import { connect } from 'react-redux'; import { setCurrentLocale } from '../../common/intl/actions'; type SwitchLocaleProps = { currentLocale: string, locales: Array<string>, setCurrentLocale: typeof setCurrentLocale, }; const SwitchLocale = ( { currentLocale, locales, setCurrentLocale }: SwitchLocaleProps, ) => ( <Box flexDirection="row" flexWrap="wrap" marginBottom={1} marginHorizontal={-0.25} > {locales.map(locale => ( <Button outline={locale !== currentLocale} key={locale} marginHorizontal={0.25} onClick={() => setCurrentLocale(locale)} primary > {locale} </Button> ))} </Box> ); export default compose( connect( (state: State) => ({ currentLocale: state.intl.currentLocale, locales: state.intl.locales, }), { setCurrentLocale }, ), )(SwitchLocale);
docs/app/Examples/collections/Table/Variations/TableExampleVeryCompact.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleVeryCompact = () => { return ( <Table compact='very'> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleVeryCompact
app/javascript/mastodon/features/generic_not_found/index.js
im-in-space/mastodon
import React from 'react'; import Column from '../ui/components/column'; import MissingIndicator from '../../components/missing_indicator'; const GenericNotFound = () => ( <Column> <MissingIndicator fullPage /> </Column> ); export default GenericNotFound;
src/Components/IconLargeFlatButtonGroup.js
charlesbao/jinjiu_mission_app
import React, { Component } from 'react'; import { Box } from './FlexBox' import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import CONSTANTS from '../Constants' const IconFlatButtonGroup = ({onTap})=>( <Box style={{margin:"10px 0"}}> <IconFlatButton label="钱包" iconClassName="ion-android-drafts" onTap={()=>onTap(CONSTANTS.ROUTER_PATH.USER.WALLET)}/> <IconFlatButton label="任务收藏" iconClassName="ion-android-favorite" onTap={()=>onTap(CONSTANTS.ROUTER_PATH.USER.FAVOUR)}/> <IconFlatButton label="设置" iconClassName="ion-android-settings" onTap={()=>onTap(CONSTANTS.ROUTER_PATH.USER.SETTING)}/> <IconFlatButton label="帮助与反馈" iconClassName="ion-android-alert" onTap={()=>onTap(CONSTANTS.ROUTER_PATH.USER.SUPPORT)}/> </Box> ); const IconFlatButton = ({label,iconClassName,onTap}) => ( <FlatButton style={button} label={label} labelStyle={{paddingLeft: 16}} icon={<FontIcon style={icon} className={iconClassName} />} onTouchTap={onTap} /> ); const button = { width:"50%", height:"auto", padding:"10px 0", lineHeight: "30px", color:"rgba(0, 0, 0, 0.541176)", borderRadius:0 }; const icon = { display:"block", fontSize:40, marginLeft:0 }; export default IconFlatButtonGroup;
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
zomeelee/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const GroupProfileMembers = React.createClass({ propTypes: { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }, mixins: [PureRenderMixin], onClick(id) { DialogActionCreators.selectDialogPeerUser(id); }, onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); }, render() { let groupId = this.props.groupId; let members = this.props.members; let myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="profile__list__item row" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} size="small" title={member.peerInfo.title}/> </a> <div className="col-xs"> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <span className="title"> {member.peerInfo.title} </span> </a> {controls} </div> </li> ); }, this); return ( <ul className="profile__list profile__list--members"> <li className="profile__list__item profile__list__item--header">{members.length} members</li> {membersList} </ul> ); } }); export default GroupProfileMembers;
client/room.js
rewired-live/assemble
import React from 'react' import { render } from 'react-dom' import { LocaleProvider } from 'antd' import enUS from 'antd/lib/locale-provider/en_US' import Main from './room/main' window.onload = () => { render( <LocaleProvider locale={enUS}> <Main /> </LocaleProvider>, document.querySelector('#reactAppContainer') ) }
common/shared/add-post/add-review/FileUpload.js
gobble43/gobble-dist-web
import React, { Component } from 'react'; import config from './../../../../env/client.js'; class FileUpload extends Component { componentDidMount() { const Dropzone = window.Dropzone; const dropzone = new Dropzone('#dropzone', { url: `${config.GOBBLE_MEDIA_URL}/api/media` }); dropzone.on('success', (err, res) => { // console.log(`image name: ${res}`); this.props.handleFile(res); }); } render() { return ( <div> <div id="dropzone" className="dropzone"> </div> </div> ); } } FileUpload.propTypes = { handleFile: React.PropTypes.func, }; export default FileUpload;
src/app/components/list/Contact.js
cherishstand/OA-react
import React from 'react'; import ReactDOM from 'react-dom'; import {List, ListItem} from 'material-ui/List'; import Drawer from 'material-ui/Drawer'; import {Link} from 'react-router'; import fetch from 'isomorphic-fetch'; import AppBar from 'material-ui/AppBar'; import Search from '../public/Search'; import MenuTotal from '../public/MenuTotal'; import RaisedButton from 'material-ui/RaisedButton'; import IconButton from 'material-ui/IconButton'; import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back'; import PhoneForwarded from 'material-ui/svg-icons/notification/phone-forwarded'; import Add from 'material-ui/svg-icons/content/add'; import {CONFIG} from '../../constants/Config'; import Template from '../public/template'; import {Tool} from '../../constants/Tools'; const styles = { title:{ textAlign: 'center', lineHeight: '45px', height: 45, overflow: 'initial', }, bar: { backgroundColor: '#fff', lineHeight: '45px', height: 45, }, phone:{ width: 16, height: 16, top: 20 }, container:{ width: '100%', height: 132, bottom: 0, top: 'none', padding: 20, transform: 'translate(0, 145px)', overflow: 'hidden' }, transform: { width: '100%', height: 132, bottom: 0, top: 'none', padding: 20, transform: 'translate(0, 0)', overflow: 'hidden' } } class Head extends React.Component { constructor(props, context) { super(props, context); } render() { return( <AppBar style={styles.bar} title={<MenuTotal items={CONFIG.contact} {...this.context}/>} titleStyle={styles.title} iconStyleLeft={{marginTop: 0,marginRight: 0}} iconStyleRight={{marginTop: 0}} iconElementLeft={<IconButton onClick={this.context.router.goBack}><ArrowBaclIcon color="#5e95c9"/></IconButton>} iconElementRight={<IconButton><Add color="#5e95c9"/></IconButton>} > </AppBar> ) } } Head.contextTypes={ fetchPosts: React.PropTypes.any, router: React.PropTypes.object } class ContactList extends React.Component { constructor(props, context){ super(props, context); this.props.fetchPosts({url: 'contacts'}) this.state={ data: [], open: false, tel: '', currentPage: 1, totalPage: 1, isFetching: false, shouldUpdata: false } this.handleClose = (event) => { this.setState({open: false}) } this.handleToggle = (event) => { let parent = event.currentTarget.parentNode; let tel = parent.querySelector('.tel').childNodes[2].nodeValue; this.setState({open: !this.state.open, tel: tel}); event.preventDefault(); } this.getNextPage = (currentPage) => { if(!this.state.shouldUpdata){ return } this.state.shouldUpdata = false this.props.getDate('/contacts', { type: 'all', limit: 8, page: currentPage}, (res) => { this.state.currentPage = currentPage; this.state.shouldUpdata = true; if(res.code === 200) { this.setState({data: this.state.data.concat(res.data)}) } else { console.log(res.code); } },'nextPage') } } getChildContext(){ return{ fetchPosts: this.props.fetchPosts } } componentDidMount(){ if(this.state.currentPage < this.state.totalPage) { Tool.nextPage(ReactDOM.findDOMNode(this.refs.container), this.state.currentPage, this.state.totalPage, this.getNextPage, this.state.shouldUpdata) } } componentWillReceiveProps(nextProps){ let { data } = nextProps.state; this.state.data = data && data.data || []; this.state.currentPage = data && data.current || 1; this.state.totalPage = data && data.pages || 1; this.state.isFetching = nextProps.state.isFetching || false; } render() { return ( <div> <div className="fiexded" > <Head /> <Search title="请输入电话号码或者联系人"/> </div> <List className="item_lists" ref='container' style={{paddingBottom: 0}}> {this.state.data&&this.state.data.map((item, index) => ( <Link to={{pathname:`/contact/${item.contactid}`, query:{url: 'contacts', mode: 4}}} key={item.contactid}> <ListItem key={item.contactid} rightIconButton={<IconButton iconStyle={styles.phone} touch={true} onTouchTap={this.handleToggle}> <PhoneForwarded color='#a2dd86'/> </IconButton>} primaryText={<p className='contact_primary'>{item.lastname}</p>} innerDivStyle={{padding: '16px 30px 16px 16px', backgroundColor: (index % 2) ? '#efeef4' : '#fff'}} rightToggle={<PhoneForwarded color='#a2dd86'/>} secondaryText={ <p className="contact_second"> <span className='company'>{<i className="material-icons">&#xE90B;</i>}{item.account_type}</span> <span className='position'>{<i className="material-icons">&#xE332;</i>}{item.contact_no}</span> <span className='tel' ref='tel'>{<i className="material-icons">&#xE551;</i>}{item.mobile}</span> </p> } /> </Link> ))} </List> <Drawer docked={false} width={200} open={this.state.open} containerStyle={this.state.open?styles.transform:styles.container} onRequestChange={(open) => this.setState({open})} > <RaisedButton fullWidth={true} backgroundColor='#82bde3' labelColor='#fff' label={this.state.tel?this.state.tel:'10000'} href={`tel:${this.state.tel}`} style={{marginBottom: 20}} onTouchTap={this.handleClose} /> <RaisedButton onTouchTap={this.handleClose} label="取消" fullWidth={true} backgroundColor='#bdbdbd' labelColor='#fff' /> </Drawer> <div className='create_menu' > <div><Link to={{pathname: '/contact/new', query: {mode: 6}}}>创建</Link></div> <div><Link to={{pathname: '/contact/fastnew', query: {mode: 6}}}>快速创建</Link></div> </div> </div> ); } } ContactList.childContextTypes = { fetchPosts: React.PropTypes.any } export default Template({ component: ContactList });
MobileApp/mstudentApp/components/Home.js
FresnoState/mobilestudentintranet
import React, { Component } from 'react'; import { Text, View, ListView, Platform } from 'react-native'; import {Icon} from 'native-base'; import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm'; import message from '../modules/message.js'; import MessageQueue from './messageViews/MessageQueue'; const dateOptions = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'}; export default class Home extends Component { static navigationOptions = { tabBarIcon: <Icon name='ios-home'/> }; constructor(props){ super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([]), date: new Date().toLocaleDateString('en-US', dateOptions), day: 'Today' }; this.currScreen = null; } componentDidMount() { //console.log("HOME", this.props.screenProps); message.getMessages((messages)=>{ this.setState({dataSource: this.state.dataSource.cloneWithRows(messages)}); }); this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => { if(notif.message) { //if data message //message.exists(notif.msi_key, (exists)=>{ //if not duplicate this.addToQueue({ "msi_key" : notif.msi_key, "topic_key" : notif.topic_key, "dist" : notif.dist, "title" : notif.title, "desc" : notif.desc, "message" : notif.message, "timestamp": Number(notif.timestamp) }); //}); } //closing iOS notification, required for being able to properly continuing receiving notifications if (Platform.OS === 'ios') { switch (notif._notificationType) { case NotificationType.Remote: notif.finish(RemoteNotificationResult.NewData); break; case NotificationType.NotificationResponse: notif.finish(); break; case NotificationType.WillPresent: notif.finish(WillPresentNotificationResult.All); break; } } } ); } componentDidUpdate(){ if(this.currScreen !== this.props.screenProps.currentScreen && this.props.screenProps.currentScreen === "Today"){ message.getMessages((messages)=>{ this.setState({dataSource: this.state.dataSource.cloneWithRows(messages)}); }); } this.currScreen = this.props.screenProps.currentScreen; } addToQueue(newMessage){ var messages = this.state.dataSource._dataBlob.s1.slice(); //slice list for re-render messages.unshift(newMessage); //add most recent message to top of the list this.setState({dataSource: this.state.dataSource.cloneWithRows(messages)}); } removeMessage(msi_key, rowID){ message.removeMessage(msi_key); var messages = this.state.dataSource._dataBlob.s1; delete messages[rowID]; this.setState({dataSource: this.state.dataSource.cloneWithRows(messages)}); } onVisibleRowChange(visibleRows, changedRows){ if(visibleRows.s1){ var rowID = Object.keys(visibleRows.s1)[0]; var timestamp = this.state.dataSource._dataBlob.s1[rowID].timestamp; var newDate = new Date(timestamp).toLocaleDateString('en-US', dateOptions); if (newDate != this.state.date) { var today = new Date(); if (newDate === today.toLocaleDateString('en-US', dateOptions)) { var newDay = "Today"; } else { var yesterday = today; yesterday.setDate(today.getDate() - 1); if (newDate === yesterday.toLocaleDateString('en-US', dateOptions)) { var newDay = "Yesterday"; } else { newDay = new Date(timestamp).toLocaleDateString('en-US', {weekday: 'long'}) } } this.setState({date: newDate, day: newDay}) } } } render() { //console.log("HOME", this.props.screenProps); return ( <View style={styles.noncentered_container}> <View style={{marginTop: 30, alignItems: 'center'}}> <Text style={styles.subHeaderText}>{this.state.date}</Text> <Text style={styles.headerText}>{this.state.day}</Text> </View> <MessageQueue messageDS={this.state.dataSource} removeMessage={this.removeMessage.bind(this)} onVisibleRowChange={this.onVisibleRowChange.bind(this)} /> </View> ); } }
app/javascript/mastodon/features/ui/components/zoomable_image.js
salvadorpla/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const MIN_SCALE = 1; const MAX_SCALE = 4; const getMidpoint = (p1, p2) => ({ x: (p1.clientX + p2.clientX) / 2, y: (p1.clientY + p2.clientY) / 2, }); const getDistance = (p1, p2) => Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2)); const clamp = (min, max, value) => Math.min(max, Math.max(min, value)); export default class ZoomableImage extends React.PureComponent { static propTypes = { alt: PropTypes.string, src: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number, onClick: PropTypes.func, } static defaultProps = { alt: '', width: null, height: null, }; state = { scale: MIN_SCALE, } removers = []; container = null; image = null; lastTouchEndTime = 0; lastDistance = 0; componentDidMount () { let handler = this.handleTouchStart; this.container.addEventListener('touchstart', handler); this.removers.push(() => this.container.removeEventListener('touchstart', handler)); handler = this.handleTouchMove; // on Chrome 56+, touch event listeners will default to passive // https://www.chromestatus.com/features/5093566007214080 this.container.addEventListener('touchmove', handler, { passive: false }); this.removers.push(() => this.container.removeEventListener('touchend', handler)); } componentWillUnmount () { this.removeEventListeners(); } removeEventListeners () { this.removers.forEach(listeners => listeners()); this.removers = []; } handleTouchStart = e => { if (e.touches.length !== 2) return; this.lastDistance = getDistance(...e.touches); } handleTouchMove = e => { const { scrollTop, scrollHeight, clientHeight } = this.container; if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) { // prevent propagating event to MediaModal e.stopPropagation(); return; } if (e.touches.length !== 2) return; e.preventDefault(); e.stopPropagation(); const distance = getDistance(...e.touches); const midpoint = getMidpoint(...e.touches); const scale = clamp(MIN_SCALE, MAX_SCALE, this.state.scale * distance / this.lastDistance); this.zoom(scale, midpoint); this.lastMidpoint = midpoint; this.lastDistance = distance; } zoom(nextScale, midpoint) { const { scale } = this.state; const { scrollLeft, scrollTop } = this.container; // math memo: // x = (scrollLeft + midpoint.x) / scrollWidth // x' = (nextScrollLeft + midpoint.x) / nextScrollWidth // scrollWidth = clientWidth * scale // scrollWidth' = clientWidth * nextScale // Solve x = x' for nextScrollLeft const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x; const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y; this.setState({ scale: nextScale }, () => { this.container.scrollLeft = nextScrollLeft; this.container.scrollTop = nextScrollTop; }); } handleClick = e => { // don't propagate event to MediaModal e.stopPropagation(); const handler = this.props.onClick; if (handler) handler(); } setContainerRef = c => { this.container = c; } setImageRef = c => { this.image = c; } render () { const { alt, src } = this.props; const { scale } = this.state; const overflow = scale === 1 ? 'hidden' : 'scroll'; return ( <div className='zoomable-image' ref={this.setContainerRef} style={{ overflow }} > <img role='presentation' ref={this.setImageRef} alt={alt} title={alt} src={src} style={{ transform: `scale(${scale})`, transformOrigin: '0 0', }} onClick={this.handleClick} /> </div> ); } }
src/Slides.js
tmpaul06/gathering-client
import React from 'react'; import UserStore from './stores/UserStore'; import { socket } from './socket'; import Background from './Background'; export default class Slides extends React.Component { constructor(props) { super(props); let masterState = UserStore.masterState || {}; this.state = { slideIndex: masterState.slideIndex || 0, slideSectionIndex: masterState.sectionIndex || [ 0 ] }; this.handlePreviousSection = this.handlePreviousSection.bind(this); this.handleNextSection = this.handleNextSection.bind(this); this.handlePreviousSlide = this.handlePreviousSlide.bind(this); this.handleNextSlide = this.handleNextSlide.bind(this); } componentDidMount() { if (!UserStore.isMaster) { socket.on('masterSlideChanged', (data) => { this.setState({ slideIndex: data.slideIndex, slideSectionIndex: data.sectionIndex }); }); } } render() { return ( <div className="slides"> <Background/> {React.Children.map(this.props.children, (child, i) => { if (this.state.slideIndex === i) { return React.cloneElement(child, { sectionIndex: this.state.slideSectionIndex[this.state.slideIndex], onPreviousSection: this.handlePreviousSection, onNextSection: this.handleNextSection, onPreviousSlide: this.handlePreviousSlide, onNextSlide: this.handleNextSlide }); } })} </div> ); } handlePreviousSlide() { if (UserStore.isMaster) { if (this.state.slideIndex > 0) { let newIndex = this.state.slideIndex - 1; let sectionIndexArr = this.state.slideSectionIndex; sectionIndexArr[newIndex] = sectionIndexArr[newIndex] || 0; this.setState({ slideIndex: newIndex }); socket.emit('slideChange', { slideIndex: newIndex, sectionIndex: sectionIndexArr }); } } } handleNextSlide() { if (UserStore.isMaster) { let childCount = React.Children.count(this.props.children); if (this.state.slideIndex < childCount - 1) { let newIndex = this.state.slideIndex + 1; let sectionIndexArr = this.state.slideSectionIndex; sectionIndexArr[newIndex] = sectionIndexArr[newIndex] || 0; this.setState({ slideIndex: newIndex, slideSectionIndex: sectionIndexArr }); socket.emit('slideChange', { slideIndex: newIndex, sectionIndex: sectionIndexArr }); } } } handlePreviousSection() { if (UserStore.isMaster) { let sectionIndexArr = this.state.slideSectionIndex; let slideIndex = this.state.slideIndex; sectionIndexArr[slideIndex] = sectionIndexArr[slideIndex] - 1; this.setState({ slideSectionIndex: sectionIndexArr }); socket.emit('slideChange', { slideIndex, sectionIndex: sectionIndexArr }); } } handleNextSection() { if (UserStore.isMaster) { let sectionIndexArr = this.state.slideSectionIndex; let slideIndex = this.state.slideIndex; sectionIndexArr[slideIndex] = sectionIndexArr[slideIndex] + 1; this.setState({ slideSectionIndex: sectionIndexArr }); socket.emit('slideChange', { slideIndex, sectionIndex: sectionIndexArr }); } } };
src/svg-icons/maps/pin-drop.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsPinDrop = (props) => ( <SvgIcon {...props}> <path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z"/> </SvgIcon> ); MapsPinDrop = pure(MapsPinDrop); MapsPinDrop.displayName = 'MapsPinDrop'; MapsPinDrop.muiName = 'SvgIcon'; export default MapsPinDrop;
app/src/Navigation.js
darjanin/xp-library
import React from 'react' import databaseUtils from './pages/utils/DatabaseUtils' export default class Navigation extends React.Component { constructor(props) { super(props) this.state = { userInfo: null, } } componentWillMount() { let userId = this.props.userId if (userId) { this.setUserInfo(userId); } } componentDidUpdate(prevProps, prevState){ if (prevProps.userId !== this.props.userId){ this.setUserInfo(this.props.userId); } } setUserInfo(id){ databaseUtils.getUserInfo(id, (userInfo) => { this.setState({ userInfo: userInfo }) }) } render() { const {changePageFn, active, loggedIn, showUser} = this.props const {userInfo} = this.state const HeaderTab = ({children, page}) => ( <a className={`header-tab ${active === page ? 'is-active' : ''}`} onClick={(e) => { e.preventDefault() changePageFn(page) }} > {children} </a> ) return ( <header className="header"> <div className="container"> <div className="header-left"> <div className="header-item" onClick={() => changePageFn('list')} > <img src="/logo.svg" alt="Logo" key="logo-image" style={{cursor: 'pointer'}}/> </div> <HeaderTab key="userList" page="userList">List of users</HeaderTab> <HeaderTab key="list" page="list">List of books</HeaderTab> {this.props.loggedIn && <HeaderTab key="add" page="add">Add new book</HeaderTab>} </div> <div className="header-right"> {loggedIn && userInfo && userInfo.username && <div className="header-item"> <button className="button is-success" onClick={(e) => { e.preventDefault() showUser() }} > {userInfo.username} </button> </div> } <div className="header-item"> <button className="button is-success" onClick={(e) => { e.preventDefault() loggedIn ? databaseUtils.logout() : changePageFn('login') }} > {loggedIn ? 'Sign Out' : 'Log In'} </button> </div> {!loggedIn && <div className="header-item"> <button className="button is-info" onClick={(e) => { e.preventDefault() changePageFn('registration') }} > Sign Up </button> </div> } </div> </div> </header> ) } }
src/components/FinishMilestone.js
tborisova/fridment-react
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom' class FinishMilestone extends Component { componentDidMount() { fetch(`/milestones/finish/${this.props.match.params.milestone_id}`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }); } render(){ return( <Redirect to={{ pathname: `/milestones`, }}/> ); }; }; export default FinishMilestone;
src/components/Architecture/Architecture.js
malinowsky/dataroot_03
/** * 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 PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Link from '../Link'; import s from './Architecture.scss'; import cx from 'classnames'; const Pics = [{link: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/13167186_1753697654861942_1634218015_n.jpg?ig_cache_key=MTI0MjM4MzkyOTE0MzgwMTg5NA%3D%3D.2.l", alt: "ok"}, {link: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/13167186_1753697654861942_1634218015_n.jpg?ig_cache_key=MTI0MjM4MzkyOTE0MzgwMTg5NA%3D%3D.2.l", alt: "ok"}, {link: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/13167186_1753697654861942_1634218015_n.jpg?ig_cache_key=MTI0MjM4MzkyOTE0MzgwMTg5NA%3D%3D.2.l", alt: "ok"}, {link: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/13167186_1753697654861942_1634218015_n.jpg?ig_cache_key=MTI0MjM4MzkyOTE0MzgwMTg5NA%3D%3D.2.l", alt: "ok"} ]; let lengthArr = Pics.length; if(lengthArr >= 6){ Pics.splice(5, (lengthArr-6)); lengthArr =6; } const Architecture = () => { let images = Pics.map((el, i) => { let link = el.link; let alt = el.alt; let boxStyle = { backgroundImage: `url(${link})`, width: "100%", height:"100%" }; return( <a href="/" alt={alt} key={i} className={s[`images${lengthArr}`]}><div className={s.photoBox} style={boxStyle}></div></a> ) }); return ( <div className={s.category}> <div className={s.categoryTitle}>Складні архітектурні вироби</div> <div className={s.categoryBlock}> {(lengthArr)? <div className={s.photoBlock}>{images}</div>: <div className={s.noPics}>Вибачте, у данному розділі фото недоступні</div>} </div> </div> )} export default withStyles(s)(Architecture);
react-ui/src/components/FourOhFour.js
civicparty/legitometer
import React from 'react' const FourOhFour = ({ }) => ( <div>Oops! This page doesn't exisit. It must be fake news. Go back to <a href="/">home</a>.</div> ) export default FourOhFour
code/workspaces/web-app/src/containers/sites/CreateSiteDialogContainer.js
NERC-CEH/datalab
import React from 'react'; import CreateStacksModalWrapper from '../modal/CreateStacksModalWrapper'; import CreateSiteDialog from '../../components/modal/CreateSiteDialog'; const CreateSiteDialogContainer = props => <CreateStacksModalWrapper Dialog={CreateSiteDialog} {...props} />; export default CreateSiteDialogContainer;
src/Parser/Warlock/Demonology/Modules/Features/DoomguardInfernal.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Combatants from 'Parser/Core/Modules/Combatants'; import calculateMaxCasts from 'Parser/Core/calculateMaxCasts'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import WilfredRing from '../Items/Legendaries/WilfredRing'; const SUMMON_COOLDOWN = 180; class DoomguardInfernal extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, wilfredRing: WilfredRing, combatants: Combatants, }; on_initialized() { this.active = !this.combatants.selected.hasTalent(SPELLS.GRIMOIRE_OF_SUPREMACY_TALENT.id); } get suggestionThresholds() { const wilfredExtraSummons = (this.wilfredRing.active) ? this.wilfredRing.extraSummons : 0; const maxCasts = Math.ceil(calculateMaxCasts(SUMMON_COOLDOWN, this.owner.fightDuration)) + wilfredExtraSummons; const doomguardCasts = this.abilityTracker.getAbility(SPELLS.SUMMON_DOOMGUARD_UNTALENTED.id).casts || 0; const infernalCasts = this.abilityTracker.getAbility(SPELLS.SUMMON_INFERNAL_UNTALENTED.id).casts || 0; const actualCasts = doomguardCasts + infernalCasts; return { actual: actualCasts, isLessThan: maxCasts, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>You should cast <SpellLink id={SPELLS.SUMMON_DOOMGUARD_UNTALENTED.id} /> or <SpellLink id={SPELLS.SUMMON_INFERNAL_UNTALENTED.id} /> more often. Doomguard is best for single target while Infernal is better for AoE. Try to pair up the cooldowns with haste buffs like <SpellLink id={SPELLS.BLOODLUST.id}/>, <SpellLink id={SPELLS.TIME_WARP.id}/> etc..</Wrapper>) .icon(SPELLS.SUMMON_DOOMGUARD_UNTALENTED.icon) .actual(`${actual} out of ${recommended} summons.`) .recommended(`${recommended} is recommended`); }); } } export default DoomguardInfernal;
assets/js/containers/TweetTimelineContainer.js
chocoelho/twitter-activities-monitor
import React from 'react'; import ReactDOM from 'react-dom'; import TweetPaginator from '../components/TweetPaginator'; import TweetModal from '../components/TweetModal' import TweetFilterContainer from '../containers/TweetFilterContainer' import Spinner from '../components/Spinner'; var TweetTimelineContainer = React.createClass({ loadTweetsFromServer: function() { $.ajax({ url: this.props.url, datatype: 'json', cache: false, success: function(data) { this.setState({data: data, completeData: data}); }.bind(this) }) }, getInitialState: function() { return { data: [], completeData: [], userFilter: '', termFilter: '', pagination: { page: 1, perPage: 5 } } }, componentDidMount: function() { this.loadTweetsFromServer(); }, handleUserFilterChange: function(event) { this.setState({userFilter: event.target.value}); }, handleTermFilterChange: function(event) { this.setState({termFilter: event.target.value}); }, render: function() { let data = this.state.data || []; const userFilter = this.state.userFilter || ''; const termFilter = this.state.termFilter || ''; if(userFilter.length > 0) { data = data.filter(function(tweet) { return tweet.user.screen_name.toLowerCase().includes(userFilter.toLowerCase()); }); } if(termFilter.length > 0) { data = data.filter(function(tweet) { return tweet.text.toLowerCase().includes(termFilter.toLowerCase()); }); } const pagination = this.state.pagination || {}; const paginated = this.paginate(data, pagination); const pages = Math.ceil(data.length / Math.max( isNaN(pagination.perPage) ? 1 : pagination.perPage, 1 )); if(data) { var tweetNodes = paginated.data.map(function(tweet, i) { return ( <div key={tweet.id} className="list-group-item list-group-item-action flex-column align-items-start"> <div className="d-flex w-100 justify-content-between"> <h5 className="mb-1">{tweet.user.screen_name}</h5> <small className="text-muted">{tweet.created_at}</small> </div> <p className="mb-1" dangerouslySetInnerHTML={{__html: tweet.text}}></p> <div className="d-flex justify-content-start w-100"> <small className="text-muted" dangerouslySetInnerHTML={{__html: tweet.source}}></small> <button className="btn btn-sm btn-outline-info ml-auto" data-target={"#modal-" + tweet.id_str} data-toggle="modal"><i className="fa fa-reply"></i></button> <TweetModal tweet={tweet} modalName={"modal-" + tweet.id_str} /> </div> </div> ) }) } return ( <div> <div className="d-flex pb-2 flex-row-reverse"> <button id="timeline-manual-refresh" className="btn btn-outline-info" onClick={this.loadTweetsFromServer}> <i className="fa fa-refresh"></i> </button> </div> <div className="row"> <div className="col-4"> <div className="list-group"> <div className="list-group-item"> <span className="mx-auto h5">Filter</span> </div> <div className="list-group-item"> <div className="input-group"> <span className="input-group-addon" id="filter-user-label"><i className="fa fa-at" aria-hidden="true"></i></span> <input type="text" className="form-control" onChange={this.handleUserFilterChange} value={this.state.userFilter} name="filter-user" id="filter-user" placeholder="by user" aria-describedby="filter-user-label" /> </div> </div> <div className="list-group-item"> <div className="input-group"> <span className="input-group-addon" id="filter-term-label"><i className="fa fa-pencil" aria-hidden="true"></i></span> <input type="text" className="form-control" placeholder="by term" onChange={this.handleTermFilterChange} value={this.state.termFilter} name="filter-term" id="filter-term" aria-describedby="filter-term-label" /> </div> </div> </div> </div> <div className="col"> <div id="tweet-timeline" className="list-group data"> {tweetNodes} <div className="mx-auto"> {data.length > 0 ? ( <TweetPaginator pagination={pagination} pages={pages} ellipsis="***" labels={{previous: 'Previous', next: 'Next'}} onSelect={this.selectPage} /> ) : ( <div className="d-flex align-items-center flex-column rounded home-common"> <div className="my-auto home-fa-inner"> <div className="p-2"> <Spinner /> </div> <h3 className="text-center p-5"> Stuck? <br /> <span className="text-muted">Try adding an user to be monitered or check filter fields</span> </h3> </div> </div> )} </div> </div> </div> </div> </div> ); }, selectPage: function(page) { const state = this.state; const pagination = this.state.pagination || {}; const pages = Math.ceil(state.data.length / pagination.perPage); pagination.page = Math.min(Math.max(page, 1), pages); this.setState({ pagination: pagination }); }, paginate: function(data, o) { data = data || []; var page = o.page - 1 || 0; var perPage = o.perPage; var amountOfPages = Math.ceil(data.length / perPage); var startPage = page < amountOfPages? page: 0; return { amount: amountOfPages, data: data.slice(startPage * perPage, startPage * perPage + perPage), page: startPage + 1 }; } }); export default TweetTimelineContainer;
src/svg-icons/image/iso.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageIso = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14zm-2-2v-1.5h-5V17h5z"/> </SvgIcon> ); ImageIso = pure(ImageIso); ImageIso.displayName = 'ImageIso'; ImageIso.muiName = 'SvgIcon'; export default ImageIso;
client/components/Root/Root.js
marcocom/portfolio-react-webpack2
import React from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; import routes from '../../routes'; import DevTools from '../DevTools'; const isProd = process.env.NODE_ENV === 'production'; export default function Root(props) { const { store, history, scrollToTop } = props; return isProd ? <Provider store={store}> <Router onUpdate={scrollToTop} history={history} routes={routes} /> </Provider> : <Provider store={store}> <div> <Router onUpdate={scrollToTop} history={history} routes={routes} /> <DevTools /> </div> </Provider>; } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired, scrollToTop: PropTypes.func.isRequired, };
fields/types/localfiles/LocalFilesField.js
michaelerobertsjr/keystone
import _ from 'lodash'; import bytes from 'bytes'; import Field from '../Field'; import React from 'react'; import { Button, FormField, FormInput, FormNote } from 'elemental'; const ICON_EXTS = [ 'aac', 'ai', 'aiff', 'avi', 'bmp', 'c', 'cpp', 'css', 'dat', 'dmg', 'doc', 'dotx', 'dwg', 'dxf', 'eps', 'exe', 'flv', 'gif', 'h', 'hpp', 'html', 'ics', 'iso', 'java', 'jpg', 'js', 'key', 'less', 'mid', 'mp3', 'mp4', 'mpg', 'odf', 'ods', 'odt', 'otp', 'ots', 'ott', 'pdf', 'php', 'png', 'ppt', 'psd', 'py', 'qt', 'rar', 'rb', 'rtf', 'sass', 'scss', 'sql', 'tga', 'tgz', 'tiff', 'txt', 'wav', 'xls', 'xlsx', 'xml', 'yml', 'zip', ]; var LocalFilesFieldItem = React.createClass({ propTypes: { deleted: React.PropTypes.bool, filename: React.PropTypes.string, isQueued: React.PropTypes.bool, size: React.PropTypes.number, toggleDelete: React.PropTypes.func, }, renderActionButton () { if (!this.props.shouldRenderActionButton || this.props.isQueued) return null; var buttonLabel = this.props.deleted ? 'Undo' : 'Remove'; var buttonType = this.props.deleted ? 'link' : 'link-cancel'; return <Button key="action-button" type={buttonType} onClick={this.props.toggleDelete}>{buttonLabel}</Button>; }, render () { const { filename } = this.props; const ext = filename.split('.').pop(); let iconName = '_blank'; if (_.includes(ICON_EXTS, ext)) iconName = ext; let note; if (this.props.deleted) { note = <FormInput key="delete-note" noedit className="field-type-localfiles__note field-type-localfiles__note--delete">save to delete</FormInput>; } else if (this.props.isQueued) { note = <FormInput key="upload-note" noedit className="field-type-localfiles__note field-type-localfiles__note--upload">save to upload</FormInput>; } return ( <FormField> <img key="file-type-icon" className="file-icon" src={Keystone.adminPath + '/images/icons/32/' + iconName + '.png'} /> <FormInput key="file-name" noedit className="field-type-localfiles__filename"> {filename} {this.props.size ? ' (' + bytes(this.props.size) + ')' : null} </FormInput> {note} {this.renderActionButton()} </FormField> ); }, }); var tempId = 0; module.exports = Field.create({ getInitialState () { var items = []; var self = this; _.forEach(this.props.value, function (item) { self.pushItem(item, items); }); return { items: items }; }, removeItem (id) { var thumbs = []; var self = this; _.forEach(this.state.items, function (thumb) { var newProps = Object.assign({}, thumb.props); if (thumb.props._id === id) { newProps.deleted = !thumb.props.deleted; } self.pushItem(newProps, thumbs); }); this.setState({ items: thumbs }); }, pushItem (args, thumbs) { thumbs = thumbs || this.state.items; args.toggleDelete = this.removeItem.bind(this, args._id); args.shouldRenderActionButton = this.shouldRenderField(); args.adminPath = Keystone.adminPath; thumbs.push(<LocalFilesFieldItem key={args._id || tempId++} {...args} />); }, fileFieldNode () { return this.refs.fileField; }, renderFileField () { return <input ref="fileField" type="file" name={this.props.paths.upload} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />; }, clearFiles () { this.fileFieldNode().value = ''; this.setState({ items: this.state.items.filter(function (thumb) { return !thumb.props.isQueued; }), }); }, uploadFile (event) { var self = this; var files = event.target.files; _.forEach(files, function (f) { self.pushItem({ isQueued: true, filename: f.name }); self.forceUpdate(); }); }, changeFiles () { this.fileFieldNode().click(); }, hasFiles () { return this.refs.fileField && this.fileFieldNode().value; }, renderToolbar () { if (!this.shouldRenderField()) return null; var clearFilesButton; if (this.hasFiles()) { clearFilesButton = <Button type="link-cancel" className="ml-5" onClick={this.clearFiles}>Clear Uploads</Button>; } return ( <div className="files-toolbar"> <Button onClick={this.changeFiles}>Upload</Button> {clearFilesButton} </div> ); }, renderPlaceholder () { return ( <div className="file-field file-upload" onClick={this.changeFiles}> <div className="file-preview"> <span className="file-thumbnail"> <span className="file-dropzone" /> <div className="ion-picture file-uploading" /> </span> </div> <div className="file-details"> <span className="file-message">Click to upload</span> </div> </div> ); }, renderContainer () { return ( <div className="files-container clearfix"> {this.state.items} </div> ); }, renderFieldAction () { var value = ''; var remove = []; _.forEach(this.state.items, function (thumb) { if (thumb && thumb.props.deleted) remove.push(thumb.props._id); }); if (remove.length) value = 'delete:' + remove.join(','); return <input ref="action" className="field-action" type="hidden" value={value} name={this.props.paths.action} />; }, renderUploadsField () { return <input ref="uploads" className="field-uploads" type="hidden" name={this.props.paths.uploads} />; }, renderNote: function () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { return ( <FormField label={this.props.label} className="field-type-localfiles" htmlFor={this.props.path}> {this.renderFieldAction()} {this.renderUploadsField()} {this.renderFileField()} {this.renderContainer()} {this.renderToolbar()} {this.renderNote()} </FormField> ); }, });
src/renderer/app.js
airtoxin/youtubar
import React from 'react'; import lodash from 'lodash'; import { render } from 'react-dom'; import { root } from 'baobab-react/higher-order'; import App from './views/App'; import tree from './tree'; import * as localStorageService from './services/localstorage'; import middlewares from './middlewares'; import apiClient from './services/api-client'; // set middlewares const mdls = lodash.reverse(middlewares.slice()); tree.on('update', (updatee) => { mdls.reduce( (next, middleware) => (tr, updt) => middleware(tr, updt, next), () => {}, )(tree, updatee); }); // restore values from local storage Object.entries(localStorageService.getAll()).forEach(([key, value]) => { tree.set(key.split('/'), value); }); tree.commit(); // set token refresher const refreshToken = () => apiClient.refreshToken().then(newToken => tree.set(['auth', 'token'], newToken)); setInterval(refreshToken, 1000 * 60); refreshToken(); const Rooted = root(tree, App); render(<Rooted />, global.window.document.getElementById('app'));
src/components/graph.js
saiteja/SvgWithReact
import React from 'react'; import Axis from './axis'; import GraphBody from './graph_body'; import Task from './task'; import Start from './start'; import Stop from './stop'; export default class Graph extends React.Component { static defaultProps = { width: 800, height: 600 }; render() { var indents = this.props.elements.map(function (i) { switch (i.type) { case 'Task': return ( <Task {...i}/> ); break; case 'Start': return ( <Start {...i}/> ); break; case 'Stop': return ( <Stop {...i}/> ); break; } }); return ( <svg width={this.props.width} height={this.props.height}> {indents} </svg> ) } }
docs/app/Examples/modules/Rating/Types/RatingExampleHeart.js
mohammed88/Semantic-UI-React
import React from 'react' import { Rating } from 'semantic-ui-react' const RatingExampleHeart = () => ( <Rating icon='heart' defaultRating={1} maxRating={3} /> ) export default RatingExampleHeart
app/components/playlist_track.js
AlienStream/experimental-frontend
import React from 'react'; class PlaylistTrack extends React.Component { render() { return ( <li className="list-group-item"> <div className="pull-right m-l"> <a href="#" className="m-r-sm"><i className="icon-heart"></i></a> <a href="#" className="m-r-sm"><i className="icon-flag"></i></a> <a href="#" className="m-r-sm"><i className="icon-plus"></i></a> </div> <a href="#" className="jp-play-me m-r-sm pull-left"> <i className="icon-control-play text"></i> <i className="icon-control-pause text-active"></i> </a> <div className="clear text-ellipsis"> <span>{this.props.title}</span> <span className="text-muted"> -- {this.props.artist}</span> </div> </li> ); } } export default PlaylistTrack
src/app/components/Number.js
XPRO-LTD/resource-managment-react
import React, { Component } from 'react'; class Number extends Component { render(){ return ( <h1 style={{color: this.props.color }}> { this.props.data } </h1> ); } } export default Number;
examples/js/basic/single-column-table.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class SingleColumnTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> </BootstrapTable> ); } }
src/svg-icons/action/https.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHttps = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </SvgIcon> ); ActionHttps = pure(ActionHttps); ActionHttps.displayName = 'ActionHttps'; ActionHttps.muiName = 'SvgIcon'; export default ActionHttps;
src/InputField/index.js
WolfgaungBeer/scado
import React from 'react'; import { oneOf, node, bool, string, func } from 'prop-types'; import fieldPropTypes from '../fieldPropTypes'; import defaultFieldPropTypes from '../defaultFieldPropTypes'; import { FieldWrapper, FieldInput } from './styled'; import Icon from '../Icon'; import Text from '../Text'; const propTypes = { ...fieldPropTypes, type: oneOf(['email', 'text', 'password', 'number', 'url']).isRequired, label: node, required: bool, className: string, onClick: func, }; const defaultProps = { ...defaultFieldPropTypes, type: undefined, label: undefined, required: undefined, className: undefined, onClick: undefined, }; const InputField = ({ input, meta, type, label, required, className, onClick }) => { const { touched, error, warning, form } = meta; const hasError = (touched && error); const hasWarning = (touched && warning); const id = `${form}-${input.name}`; return ( <FieldWrapper className={className} onClick={onClick}> {label && <Text.Label htmlFor={id}>{label} {required && <Text.Span color="error">*</Text.Span>}</Text.Label>} <FieldInput id={id} type={type} {...input} /> {hasError && <Text.Span color="error" scale="s"><Icon color="error" scale="s">clear</Icon> {error}</Text.Span>} {hasWarning && <Text.Span color="warning" scale="s"><Icon color="warning" scale="s">warning</Icon> {warning}</Text.Span>} </FieldWrapper> ); }; InputField.propTypes = propTypes; InputField.defaultProps = defaultProps; export default InputField;
MobileApp/node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/actual.js
VowelWeb/CoinTradePros.com
import React, { Component } from 'react'; class Foo extends Component { render() {} }
src/client.js
codejunkienick/katakana
/** * 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 ga from 'react-ga'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect } from 'redux-connect'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import getRoutes from './routes'; const client = new ApiClient(); const _browserHistory = useScroll(() => browserHistory)(); const dest = document.getElementById('content'); const store = createStore(_browserHistory, client, window.__data); const history = syncHistoryWithStore(_browserHistory, store); require('../static/fonts/lato/scss/lato.scss'); const asci = ` ______ ____________________________ _____________ ________ ___ //_/__ |__ __/__ |__ //_/__ |__ | / /__ | __ ,< __ /| |_ / __ /| |_ ,< __ /| |_ |/ /__ /| | _ /| | _ ___ | / _ ___ | /| | _ ___ | /| / _ ___ | /_/ |_| /_/ |_/_/ /_/ |_/_/ |_| /_/ |_/_/ |_/ /_/ |_| `; console.log(asci); console.log("Если вы хотите вступить в группу разработчиков KATAKANA, обращайтесь по адрессу mail@katakana.xyz"); console.log("Если вам интересна не только сгенерированная верстка, приглашаю вас посетить репозиторий на github: http://github.com/codejunkienick/katakana"); if (process.env.NODE_ENV === 'production') { ga.initialize('UA-78109937-1'); } function logPageView() { if (process.env.NODE_ENV === 'production') { ga.pageview(window.location.pathname); } } function initSocket() { const socket = io('', {path: '/ws'}); return socket; } //global.socket = initSocket(); const component = ( <Router render={(props) => <ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} /> } history={history} onUpdate={logPageView}> {getRoutes(store)} </Router> ); 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__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
packages/editor/src/core/maps.js
strues/boldr
import React from 'react'; export const getHeadings = lang => [ { key: 'header-one', title: `${lang.controls.header} 1`, text: <h1>{lang.controls.header} 1</h1>, type: 'block-type', command: 'header-one', }, { key: 'header-two', title: `${lang.controls.header} 2`, text: <h2>{lang.controls.header} 2</h2>, type: 'block-type', command: 'header-two', }, { key: 'header-three', title: `${lang.controls.header} 3`, text: <h3>{lang.controls.header} 3</h3>, type: 'block-type', command: 'header-three', }, { key: 'header-four', title: `${lang.controls.header} 4`, text: <h4>{lang.controls.header} 4</h4>, type: 'block-type', command: 'header-four', }, { key: 'header-five', title: `${lang.controls.header} 5`, text: <h5>{lang.controls.header} 5</h5>, type: 'block-type', command: 'header-five', }, { key: 'header-six', title: `${lang.controls.header} 6`, text: <h6>{lang.controls.header} 6</h6>, type: 'block-type', command: 'header-six', }, ]; export const blocks = { 'header-one': 'h1', 'header-two': 'h2', 'header-three': 'h3', 'header-four': 'h4', 'header-fiv': 'h5', 'header-six': 'h6', unstyled: 'p', blockquote: 'blockquote', code: 'em', };
mixins/ContainerMixin.js
FaridSafi/react-native-gifted-form
import React from 'react'; import PropTypes from 'prop-types'; import { ScrollView, View, Platform, Dimensions } from 'react-native'; var GiftedFormManager = require('../GiftedFormManager'); module.exports = { propTypes: { formName: PropTypes.string, scrollOnTap: PropTypes.bool, scrollEnabled: PropTypes.bool, formStyles: PropTypes.object, // navigator: , }, getDefaultProps() { return { formName: 'form', scrollOnTap: true, // auto scroll when focus textinput in bottom of screen scrollEnabled: true, formStyles: {}, navigator: null, // @todo test when null if crash } }, getInitialState() { return { errors: [], }; }, _onTouchStart(e) { this._pageY = e.nativeEvent.pageY; this._locationY = e.nativeEvent.locationY; }, _onScroll(e) { this._y = e.nativeEvent.contentOffset.y; }, // https://facebook.github.io/react-native/docs/nativemethodsmixin.html#content // I guess it can be improved by using height measures handleFocus(scrollToTopOfWidget = false) { if (Platform.OS !== 'android' && this.props.scrollEnabled === true) { var keyboardHeight = 259; if (this.props.scrollOnTap === true && this._pageY + this._locationY > Dimensions.get('window').height - keyboardHeight - 44) { // @todo don't scroll lower than _contentSize if (scrollToTopOfWidget === true) { this._scrollResponder.scrollTo({ y: this._pageY - this._locationY - 44 - 30, x: 0, animated: false, }); } else { this._scrollResponder.scrollTo({ y: this._pageY + this._y - this._locationY - keyboardHeight + 44, x: 0, animated: false, }); } } // @todo don't change inset if external keyboard connected this.refs.container.setNativeProps({ contentInset: {top: 0, bottom: keyboardHeight, left: 0, right: 0}, }); } }, handleBlur() { if (Platform.OS !== 'android' && this.props.scrollEnabled === true) { // @todo dont change inset if external keyboard connected this.refs.container.setNativeProps({ contentInset: {top: 0, bottom: 0, left: 0, right: 0}, }); } }, handleValidation() { if (!this.props.onValidation) return; var validation = GiftedFormManager.validate(this.props.formName); this.props.onValidation(validation); }, handleValueChange() { if (!this.props.onValueChange) return; var values = GiftedFormManager.getValues(this.props.formName); this.props.onValueChange(values); }, childrenWithProps() { return React.Children.map(this.props.children, (child) => { if (!!child) { return React.cloneElement(child, { formStyles: this.props.formStyles, openModal: this.props.openModal, formName: this.props.formName, form: this, navigator: this.props.navigator, onFocus: this.handleFocus, onBlur: this.handleBlur, onValidation: this.handleValidation, onValueChange: this.handleValueChange, }); } }); }, componentDidMount() { this._y = 0; this._pageY = 0; this._locationY = 0; if (this.props.scrollEnabled === true) { this._scrollResponder = this.refs.container.getScrollResponder(); } }, _renderContainerView() { var formStyles = this.props.formStyles; var viewStyle = [(this.props.isModal === false ? [styles.containerView, formStyles.containerView] : [styles.modalView, formStyles.modalView]), this.props.style]; if (this.props.scrollEnabled === true) { return ( <ScrollView ref='container' style={viewStyle} automaticallyAdjustContentInsets={false} keyboardDismissMode='on-drag' keyboardShouldPersistTaps="always" onTouchStart={this.props.scrollOnTap === true ? this._onTouchStart : null} onScroll={this.props.scrollOnTap === true ? this._onScroll : null} scrollEventThrottle={this.props.scrollOnTap === true ? 200 : 0} {...this.props} > {this.childrenWithProps()} </ScrollView> ); } return ( <View ref='container' style={viewStyle} keyboardDismissMode='on-drag' // its working on View ? {...this.props} > {this.childrenWithProps()} </View> ); }, }; var styles = { containerView: { backgroundColor: '#eee', flex: 1, }, modalView: { backgroundColor: '#eee', flex: 1, }, };
addons/a11y/.storybook/components/Button/component.js
rhalff/storybook
import React from 'react'; import PropTypes from 'prop-types'; const styles = { button: { padding: '12px 6px', fontSize: '12px', lineHeight: '16px', borderRadius: '5px', }, ok: { backgroundColor: '#028402', color: '#ffffff', }, wrong: { color: '#ffffff', backgroundColor: '#4caf50', }, }; function Button({ content, disabled, contrast }) { return ( <button style={{ ...styles.button, ...styles[contrast], }} disabled={disabled} > {content} </button> ); } Button.propTypes = { content: PropTypes.string, disabled: PropTypes.bool, contrast: PropTypes.oneOf(['ok', 'wrong']), }; Button.defaultProps = { content: 'null', disabled: false, contrast: 'ok', }; export default Button;
views/notfound_page.js
SpaceyRezum/react-trivia-game
import React from 'react'; import { Link } from 'react-router'; class PageNotFound extends React.Component { render() { return ( <div className="page-not-found-container"> <p>Oh no! It looks like you've gone off-path!</p> <p>For your safety, please head back to the <Link to="/">main page and check out our quizzes</Link>!</p> </div> ) } } export default PageNotFound;
src/svg-icons/hardware/laptop.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareLaptop = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"/> </SvgIcon> ); HardwareLaptop = pure(HardwareLaptop); HardwareLaptop.displayName = 'HardwareLaptop'; HardwareLaptop.muiName = 'SvgIcon'; export default HardwareLaptop;
src/components/PrevNext/PrevNext.js
joyvuu-dave/comeals-ui-react
// rendered by DateBox import React from 'react' import { Link } from 'react-router' import classes from './PrevNext.scss' type Props = { prevId: number, nextId: number, ui: { disabled: boolean, hidden: boolean } }; export class PrevNext extends React.Component<void, Props, void> { constructor () { super() this.handleLinkClick = this.handleLinkClick.bind(this) } handleLinkClick (event) { if (this.props.ui.disabled) { event.preventDefault() } } render () { return ( <section> <Link onClick={this.handleLinkClick} className={this.props.prevId && !this.props.ui.hidden ? classes.link : classes.hide} to={`/meals/${this.props.prevId}`}> <div className={classes['icono-previous']}></div> Prev </Link> {' '} <Link onClick={this.handleLinkClick} className={this.props.nextId && !this.props.ui.hidden ? classes.link : classes.hide} to={`/meals/${this.props.nextId}`}> Next <div className={classes['icono-next']}></div> </Link> {' '} <Link onClick={this.handleLinkClick} className={this.props.ui.hidden ? classes.hide : classes.link} to={'/'}>Calendar</Link> </section> ) } } export default PrevNext
src/Pagination.js
andrew-d/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import PaginationButton from './PaginationButton'; import CustomPropTypes from './utils/CustomPropTypes'; import SafeAnchor from './SafeAnchor'; const Pagination = React.createClass({ mixins: [BootstrapMixin], propTypes: { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, ellipsis: React.PropTypes.bool, first: React.PropTypes.bool, last: React.PropTypes.bool, prev: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: CustomPropTypes.elementType }, getDefaultProps() { return { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, buttonComponentClass: SafeAnchor, bsClass: 'pagination' }; }, renderPageButtons() { let pageButtons = []; let startPage, endPage, hasHiddenPagesAfter; let { maxButtons, activePage, items, onSelect, ellipsis, buttonComponentClass } = this.props; if(maxButtons){ let hiddenPagesBefore = activePage - parseInt(maxButtons / 2); startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1; hasHiddenPagesAfter = startPage + maxButtons <= items; if(!hasHiddenPagesAfter){ endPage = items; startPage = items - maxButtons + 1; if(startPage < 1){ startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for(let pagenumber = startPage; pagenumber <= endPage; pagenumber++){ pageButtons.push( <PaginationButton key={pagenumber} eventKey={pagenumber} active={pagenumber === activePage} onSelect={onSelect} buttonComponentClass={buttonComponentClass}> {pagenumber} </PaginationButton> ); } if(maxButtons && hasHiddenPagesAfter && ellipsis){ pageButtons.push( <PaginationButton key='ellipsis' disabled buttonComponentClass={buttonComponentClass}> <span aria-label='More'>...</span> </PaginationButton> ); } return pageButtons; }, renderPrev() { if(!this.props.prev){ return null; } return ( <PaginationButton key='prev' eventKey={this.props.activePage - 1} disabled={this.props.activePage === 1} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Previous'>&lsaquo;</span> </PaginationButton> ); }, renderNext() { if(!this.props.next){ return null; } return ( <PaginationButton key='next' eventKey={this.props.activePage + 1} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Next'>&rsaquo;</span> </PaginationButton> ); }, renderFirst() { if(!this.props.first){ return null; } return ( <PaginationButton key='first' eventKey={1} disabled={this.props.activePage === 1 } onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='First'>&laquo;</span> </PaginationButton> ); }, renderLast() { if(!this.props.last){ return null; } return ( <PaginationButton key='last' eventKey={this.props.items} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Last'>&raquo;</span> </PaginationButton> ); }, render() { return ( <ul {...this.props} className={classNames(this.props.className, this.getBsClassSet())}> {this.renderFirst()} {this.renderPrev()} {this.renderPageButtons()} {this.renderNext()} {this.renderLast()} </ul> ); } }); export default Pagination;