path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
client/src/components/systems/Container.js
DjLeChuck/recalbox-manager
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { translate } from 'react-i18next'; import { grep, translatableConf, save } from '../../api'; import { promisifyData, cancelPromises } from '../../utils'; import Systems from './Systems'; class SystemContainer extends Component { static propTypes = { t: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { loaded: false, saving: false, stickyContent: null, stickyStyle: 'danger', }; } async componentWillMount() { const state = await promisifyData( translatableConf(['recalbox.systems.ratio', 'recalbox.systems.shaderset']), grep([ 'global.ratio', 'global.shaderset', 'global.smooth', 'global.rewind', 'global.autosave', 'global.integerscale', 'global.retroachievements', 'global.retroachievements.hardcore', 'global.retroachievements.username', 'global.retroachievements.password', ]) ); state.loaded = true; this.setState(state); } componentWillUnmount() { cancelPromises(); } onSubmit = (values) => { const { t } = this.props; this.setState({ saving: true }); save(values).then(() => ( this.setState({ saving: false, stickyContent: t('La configuration a bien été sauvegardée.'), stickyStyle: 'success', }) ), () => ( this.setState({ saving: false, stickyContent: t('Une erreur est survenue lors de la sauvegarde de la configuration.'), stickyStyle: 'danger', }) )); }; render() { return ( <Systems {...this.state} onSubmit={this.onSubmit} dataset={{ ratioList: this.state['recalbox.systems.ratio'], shadersets: this.state['recalbox.systems.shaderset'], }} defaultValues={{ 'global.ratio': this.state['global.ratio'], 'global.shaderset': this.state['global.shaderset'], 'global.smooth': this.state['global.smooth'], 'global.rewind': this.state['global.rewind'], 'global.autosave': this.state['global.autosave'], 'global.integerscale': this.state['global.integerscale'], 'global.retroachievements': this.state['global.retroachievements'], 'global.retroachievements.hardcore': this.state['global.retroachievements.hardcore'], 'global.retroachievements.username': this.state['global.retroachievements.username'], 'global.retroachievements.password': this.state['global.retroachievements.password'], }} /> ); } } export default translate()(SystemContainer);
assets/javascripts/archon/pages/AppDetailPage.js
panli889/archon
import React from 'react'; import {History} from 'react-router'; import * as AppActions from '../models/actions/Apps'; import MDL from '../components/MdlComponents'; import AppSummaryCard from '../components/AppSummaryCard'; import CreateAppCard from '../components/CreateAppCard'; import AppProcDetailCard from '../components/AppProcDetailCard'; import AppServicePortalCard from '../components/AppServicePortalCard'; import LoadHud from '../components/LoadHud'; import NoticeInforCard from '../components/NoticeInforCard'; import AuthorizeMixin from '../mixins/AuthorizeMixin'; import FlashMessageMixin from '../mixins/FlashMessageMixin'; import ApiMixin from '../mixins/ApiMixin'; import AppView from '../models/views/App'; import ProcView from '../models/views/Proc'; let AppDetailPage = React.createClass({ mixins: [History, AuthorizeMixin, FlashMessageMixin, ApiMixin], componentDidMount() { this.authorize(() => { this.refreshApp(); }); }, componentWillReceiveProps(nextProps) { const name = this.getAppName(); const newName = nextProps.params.name; if (newName !== name) { this.authorize(() => { this.refreshApp(nextProps); }); } else { const request = this.getRequestFromProps(nextProps, 'DELETE_APP_REQUEST'); if (request.statusCode === 202) { // app got deleted this.history.pushState(null, '/archon/apps'); } } }, render() { const name = this.getAppName(); const { requests, isFetching, error } = this.getPageRequests(['GET_APP_REQUEST', 'UPGRADE_APP_REQUEST', 'DELETE_APP_REQUEST', 'ROLLBACK_APP_REQUEST']); const [request, upgradeReq, deleteReq, rollbackReq] = requests; return ( <MDL.Grid> <MDL.GridCell col={8}> { this.renderFlash(upgradeReq.opFlash, AppActions.resetApiFlash('UPGRADE_APP_REQUEST')) } { !error ? null : <NoticeInforCard title='请求出错了' noticeType='error' buttons={[ { title: '刷新', color: 'colored', onClick: this.refreshApp }, ]} message={`应用操作 - ${name} 失败:${error}`} /> } { this.renderApp(request) } </MDL.GridCell> <MDL.GridCell col={4}> <CreateAppCard /> { error || isFetching ? null : <NoticeInforCard title={`升级应用`} noticeType='info' buttons={[ { title: '升级', icon: 'trending_up', color: 'accent', onClick: (evt) => this.upgradeApp(name) }, ]} message={`推送最新版的应用Image之后,可以点击升级按钮对本应用进行升级。`} /> } { error || isFetching ? null : <NoticeInforCard title={`回滚应用`} noticeType='info' buttons={[ { title: '回滚', icon: 'trending_up', color: 'accent', onClick: (evt) => this.rollbackApp(name) }, ]} message={`回滚应用将会使用用户指定的应用版本进行部署。`} /> } { error || isFetching ? null : <NoticeInforCard title={`删除应用`} noticeType='error' buttons={[ { title: '删除', icon: 'highlight_remove', color: 'accent', onClick: (evt) => this.deleteApp(name) }, ]} message={`删除应用将会移除所有本App在集群中的运行容器,但是会保留本应用的注册信息,之后还可以重新部署。`} /> } </MDL.GridCell> { isFetching ? <LoadHud /> : null } </MDL.Grid> ); }, renderApp(request) { const appName = this.getAppName(); if (request.statusCode !== 200) { return null; } const app = request.data; return ( <div> <AppSummaryCard app={app} inDetail={true} onRefreshClick={this.refreshApp} /> { app.procs.map((proc, index) => <AppProcDetailCard proc={ProcView(proc)} app={AppView(app)} key={index} />) } { app.useservices.map((us, index) => { const service = us.service; if (!service.portals) { return null; } return ( <div key={index}> { service.portals.map((portal, pIndex) => <AppServicePortalCard service={service} app={AppView(app)} portal={ProcView(portal)} key={pIndex} />) } </div> ); }) } </div> ); }, refreshApp(props = this.props) { const {dispatch} = props; const name = this.getAppName(props); if (name) { dispatch(AppActions.resetApiCall('UPGRADE_APP_REQUEST')); dispatch(AppActions.resetApiCall('DELETE_APP_REQUEST')); dispatch(AppActions.resetApiCall('ROLLBACK_APP_REQUEST')); dispatch(AppActions.get(name)); } else { this.history.replaceState(null, '/archon'); } }, upgradeApp(name) { if (confirm(`确定要升级应用-${name}吗?`)) { const {dispatch} = this.props; dispatch(AppActions.resetApiCall('UPGRADE_APP_REQUEST')); dispatch(AppActions.resetApiCall('DELETE_APP_REQUEST')); dispatch(AppActions.resetApiCall('ROLLBACK_APP_REQUEST')); name && dispatch(AppActions.upgrade(name)); } }, deleteApp(name) { if (confirm(`确定要删除应用-${name}吗?`)) { const {dispatch} = this.props; dispatch(AppActions.resetApiCall('UPGRADE_APP_REQUEST')); dispatch(AppActions.resetApiCall('DELETE_APP_REQUEST')); dispatch(AppActions.resetApiCall('ROLLBACK_APP_REQUEST')); name && dispatch(AppActions.remove(name)); } }, rollbackApp(name){ const {dispatch} = this.props; dispatch(AppActions.resetApiCall('UPGRADE_APP_REQUEST')); dispatch(AppActions.resetApiCall('DELETE_APP_REQUEST')); dispatch(AppActions.resetApiCall('ROLLBACK_APP_REQUEST')); this.history.pushState(null, `/archon/apps/${name}/versions`); }, getAppName(props = this.props) { return props.params.name; }, }); export default AppDetailPage;
src/components/Header/index.js
jahammo2/portfolio-web_client
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './index.scss'; import MenuBar from '../../components/MenuBar'; import { Link } from 'react-router'; const propTypes = { children: PropTypes.node, handleOpenSideBar: PropTypes.func, sideBarShown: PropTypes.func, sideBarShowing: PropTypes.bool }; class Header extends Component { title () { if (window.innerWidth > 768) { return 'projects'; } return 'menu'; } iconClassName () { if (this.props.sideBarShowing) { return 'times'; } return 'bars'; } render () { return ( <div className='header column-between'> <div className='header__container row-between'> <Link className='header__name' onClick={this.props.handleOpenSideBar} to='/' > Jordan Hammond </Link> <div className='header__vertical-line mobile' /> <MenuBar handleOpenSideBar={this.props.handleOpenSideBar} sideBarShown={this.props.sideBarShown} sideBarShowing={this.props.sideBarShowing} title={this.title()} /> </div> <hr className='header__line line' /> </div> ); } } Header.propTypes = propTypes; export default Header;
src/svg-icons/content/text-format.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentTextFormat = (props) => ( <SvgIcon {...props}> <path d="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z"/> </SvgIcon> ); ContentTextFormat = pure(ContentTextFormat); ContentTextFormat.displayName = 'ContentTextFormat'; ContentTextFormat.muiName = 'SvgIcon'; export default ContentTextFormat;
react/src/components/dashboard/tools/toolsTxPush.js
pbca26/EasyDEX-GUI
import React from 'react'; import translate from '../../../translate/translate'; import addCoinOptionsCrypto from '../../addcoin/addcoinOptionsCrypto'; import addCoinOptionsAC from '../../addcoin/addcoinOptionsAC'; import Select from 'react-select'; import { triggerToaster, copyString, apiToolsBalance, apiToolsBuildUnsigned, apiToolsPushTx, apiToolsSeedToWif, apiToolsWifToKP, apiElectrumListunspent, apiCliPromise, apiElectrumSplitUtxoPromise, } from '../../../actions/actionCreators'; import Store from '../../../store'; import QRCode from 'qrcode.react'; import QRModal from '../qrModal/qrModal'; import { explorerList } from 'agama-wallet-lib/src/coin-helpers'; import devlog from '../../../util/devlog'; const { shell } = window.require('electron'); class ToolsTxPush extends React.Component { constructor() { super(); this.state = { sendFrom: '', sendTo: '', amount: 0, selectedCoin: '', balance: null, tx2qr: null, utxo: null, rawTx2Push: null, txPushResult: null, }; this.updateInput = this.updateInput.bind(this); this.updateSelectedCoin = this.updateSelectedCoin.bind(this); this.sendTx = this.sendTx.bind(this); this.copyTx = this.copyTx.bind(this); } copyTx() { Store.dispatch(copyString(this.state.txPushResult, translate('TOOLS.TXID_COPIED'))); } sendTx() { apiToolsPushTx( this.state.selectedCoin.split('|')[0].toLowerCase(), this.state.rawTx2Push ) .then((res) => { devlog(res); this.setState({ txPushResult: res.result, }); }); } renderCoinOption(option) { return ( <div> <img src={ `assets/images/cryptologo/${option.icon.toLowerCase()}.png` } alt={ option.label } width="30px" height="30px" /> <span className="margin-left-10">{ option.label }</span> </div> ); } updateSelectedCoin(e, propName) { if (e && e.value && e.value.indexOf('|')) { this.setState({ [propName]: e.value, }); } } updateInput(e) { this.setState({ [e.target.name]: e.target.value, }); } openExplorerWindow(txid) { const _coin = this.state.selectedCoin.split('|')[0].toUpperCase(); const url = explorerList[_coin].split('/').length - 1 > 2 ? `${explorerList[_coin]}${txid}` : `${explorerList[_coin]}/tx/${txid}`; return shell.openExternal(url); } render() { return ( <div className="row margin-left-10"> <div className="col-xlg-12 form-group form-material no-padding-left padding-bottom-10"> <h4>{ translate('TOOLS.PUSH_RAW_TX') }</h4> </div> <div className="col-xlg-12 form-group form-material no-padding-left padding-top-20 padding-bottom-50"> <label className="control-label col-sm-1 no-padding-left" htmlFor="kmdWalletSendTo"> { translate('TOOLS.COIN') } </label> <Select name="selectedCoin" className="col-sm-3" value={ this.state.selectedCoin } onChange={ (event) => this.updateSelectedCoin(event, 'selectedCoin') } optionRenderer={ this.renderCoinOption } valueRenderer={ this.renderCoinOption } options={ addCoinOptionsCrypto('skip', true, false) .concat(addCoinOptionsAC('skip')) } /> </div> <div className="col-sm-12 form-group form-material no-padding-left margin-top-20"> <textarea rows="5" cols="20" name="rawTx2Push" className="col-sm-7 no-padding-left" placeholder={ translate('TOOLS.TX_TO_PUSH') } onChange={ this.updateInput } value={ this.state.rawTx2Push }></textarea> </div> <div className="col-sm-12 form-group form-material no-padding-left margin-top-10 padding-bottom-10"> <button type="button" className="btn btn-info col-sm-2" onClick={ this.sendTx }> { translate('TOOLS.PUSH') } </button> </div> { this.state.txPushResult && <div className="col-sm-12 form-group form-material no-padding-left margin-top-20"> { this.state.txPushResult.length === 64 && <div> <div className="margin-bottom-15"> { this.state.selectedCoin.split('|')[0].toUpperCase() } { translate('TOOLS.TX_PUSHED') }! </div> <div> { translate('KMD_NATIVE.TXID') }: <div className="blur selectable word-break--all margin-left-5"> { this.state.txPushResult } <button className="btn btn-default btn-xs clipboard-edexaddr margin-left-20" title={ translate('INDEX.COPY_TO_CLIPBOARD') } onClick={ this.copyTx }> <i className="icon wb-copy"></i> { translate('INDEX.COPY') } </button> </div> <div className="margin-top-10"> <button type="button" className="btn btn-sm white btn-dark waves-effect waves-light pull-left" onClick={ () => this.openExplorerWindow(this.state.txPushResult) }> <i className="icon fa-external-link"></i> { translate('INDEX.OPEN_TRANSACTION_IN_EPLORER', this.state.selectedCoin.split('|')[0].toUpperCase()) } </button> </div> </div> </div> } { this.state.txPushResult.length !== 64 && <div> <strong>{ translate('TOOLS.ERROR') }:</strong> <div className="selectable word-break--all">{ JSON.stringify(this.state.txPushResult) }</div> </div> } </div> } </div> ); } } export default ToolsTxPush;
src/svg-icons/content/send.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentSend = (props) => ( <SvgIcon {...props}> <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/> </SvgIcon> ); ContentSend = pure(ContentSend); ContentSend.displayName = 'ContentSend'; ContentSend.muiName = 'SvgIcon'; export default ContentSend;
app/scripts/TilesetFinder.js
hms-dbmi/higlass
import React from 'react'; import PropTypes from 'prop-types'; import slugid from 'slugid'; import CheckboxTree from 'react-checkbox-tree'; import { tileProxy } from './services'; import '../styles/TilesetFinder.css'; import withPubSub from './hocs/with-pub-sub'; // Configs import { TRACKS_INFO } from './configs'; class TilesetFinder extends React.Component { constructor(props) { super(props); // this.localTracks = TRACKS_INFO.filter // local tracks are ones that don't have a filetype associated with them this.localTracks = TRACKS_INFO.filter((x) => x.local && !x.hidden).map( (x) => { const y = Object.assign({}, x); y.datatype = x.datatype[0]; return y; }, ); this.augmentedTracksInfo = TRACKS_INFO; if (window.higlassTracksByType) { Object.keys(window.higlassTracksByType).forEach((pluginTrackType) => { this.augmentedTracksInfo.push( window.higlassTracksByType[pluginTrackType].config, ); }); } if (props.datatype) { this.localTracks = this.localTracks.filter( (x) => x.datatype[0] === props.datatype, ); } else { this.localTracks = this.localTracks.filter( (x) => x.orientation === this.props.orientation, ); } this.localTracks.forEach((x) => { x.uuid = slugid.nice(); }); const newOptions = this.prepareNewEntries('', this.localTracks, {}); const availableTilesetKeys = Object.keys(newOptions); const selectedUuid = availableTilesetKeys.length ? [availableTilesetKeys[0]] : null; this.mounted = false; this.state = { selectedUuid, options: newOptions, filter: '', checked: [], expanded: [], }; this.requestTilesetLists(); } componentDidMount() { // we want to query for a list of tracks that are compatible with this // track orientation this.mounted = true; this.requestTilesetLists(); this.searchBox.focus(); } componentWillUnmount() { this.mounted = false; } prepareNewEntries(sourceServer, newEntries, existingOptions) { /** * Add meta data to new tileset entries before adding * them to the list of available options. */ const newOptions = existingOptions; const entries = newEntries.map((ne) => { const ane = Object.assign({}, ne, { server: sourceServer, tilesetUid: ne.uuid, serverUidKey: this.serverUidKey(sourceServer, ne.uuid), datatype: ne.datatype, name: ne.name, uid: slugid.nice(), }); return ane; }); entries.forEach((ne) => { newOptions[ne.serverUidKey] = ne; }); return newOptions; } serverUidKey(server, uid) { /** * Create a key for a server and uid */ return `${server}/${uid}`; } requestTilesetLists() { let datatypesQuery = null; if (this.props.datatype) { datatypesQuery = `dt=${this.props.datatype}`; } else { const datatypes = new Set( [].concat( ...this.augmentedTracksInfo .filter((x) => x.datatype) .filter((x) => { return ( x.orientation === this.props.orientation || (this.props.orientation === '1d-vertical' && x.orientation === '1d-horizontal') ); }) .map((x) => x.datatype), ), ); datatypesQuery = [...datatypes].map((x) => `dt=${x}`).join('&'); } if (!this.props.trackSourceServers) { console.warn('No track source servers specified in the viewconf'); return; } this.props.trackSourceServers.forEach((sourceServer) => { tileProxy.json( `${sourceServer}/tilesets/?limit=10000&${datatypesQuery}`, (error, data) => { if (error) { console.error('ERROR:', error); } else { const newOptions = this.prepareNewEntries( sourceServer, data.results, this.state.options, ); const availableTilesetKeys = Object.keys(newOptions); let { selectedUuid } = this.state; // if there isn't a selected tileset, select the first received one if (!selectedUuid) { selectedUuid = availableTilesetKeys.length ? [availableTilesetKeys[0]] : null; const selectedTileset = this.state.options[selectedUuid[0]]; this.props.selectedTilesetChanged([selectedTileset]); } if (this.mounted) { this.setState({ selectedUuid, options: newOptions, }); } } }, this.props.pubSub, ); }); } /** * Double clicked on an element. Should be selected * and this window will be closed. */ handleOptionDoubleClick(x /* , y */) { const value = this.state.options[x.target.value]; this.props.onDoubleClick(value); } handleSelectedOptions(selectedOptions) { const selectedValues = []; const selectedTilesets = []; // I don't know why selectedOptions.map doesn't work for (let i = 0; i < selectedOptions.length; i++) { selectedValues.push(selectedOptions[i]); selectedTilesets.push(this.state.options[selectedOptions[i]]); } this.props.selectedTilesetChanged(selectedTilesets); this.setState({ selectedUuid: selectedValues }); } handleSelect() { const { selectedOptions } = this.multiSelect; const selectedOptionsList = []; for (let i = 0; i < selectedOptions.length; i++) { const selectedOption = selectedOptions[i]; selectedOptionsList.push(selectedOption.value); } this.handleSelectedOptions(selectedOptionsList); } handleSearchChange() { const domElement = this.searchBox; this.setState({ filter: domElement.value }); } /* * Create the nested checkbox tree by partitioning the * list of available datasets according to their group * * @param {object} datasetsDict A dictionary of id -> tileset * def mappings * @param {string} filter A string to filter the results by * @returns {array} A list of items that define the nested checkbox * structure * { * 'name': 'blah', * 'value': 'blah', * 'children': [], * } */ partitionByGroup(datasetsDict, filter) { const itemsByGroup = { '': { name: '', value: '', children: [], }, }; for (const uuid of Object.keys(datasetsDict)) { const item = datasetsDict[uuid]; if (!item.name.toLowerCase().includes(filter)) { continue; } if ('project_name' in item) { const group = item.project_name; if (!(group in itemsByGroup)) { itemsByGroup[group] = { value: group, label: group, children: [], }; } itemsByGroup[group].children.push({ label: item.name, value: uuid, }); } else { itemsByGroup[''].children.push({ label: item.name, value: uuid, }); } } const allItems = itemsByGroup[''].children; // coollapse the group lists into one list of objects for (const group of Object.keys(itemsByGroup)) { if (group !== '') { itemsByGroup[group].children.sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase(), 'en'), ); allItems.push(itemsByGroup[group]); } } allItems.sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase(), 'en'), ); return allItems; } handleChecked(checked) { this.handleSelectedOptions(checked); this.setState({ checked }); } handleExpanded(expanded) { this.setState({ expanded }); } render() { const optionsList = []; for (const key in this.state.options) { optionsList.push(this.state.options[key]); } const nestedItems = this.partitionByGroup( this.state.options, this.state.filter, ); const svgStyle = { width: 15, height: 15, top: 2, right: 2, position: 'relative', }; const halfSvgStyle = JSON.parse(JSON.stringify(svgStyle)); halfSvgStyle.opacity = 0.5; const form = ( <form onSubmit={(evt) => { evt.preventDefault(); }} > <div className="tileset-finder-search-bar"> <span className="tileset-finder-label">Select tileset:</span> <input ref={(c) => { this.searchBox = c; }} className="tileset-finder-search-box" onChange={this.handleSearchChange.bind(this)} placeholder="Search Term" type="text" /> </div> <div className="tileset-finder-checkbox-tree" styleName="tileset-finder-checkbox-tree" > <CheckboxTree checked={this.state.checked} expanded={this.state.expanded} icons={{ uncheck: ( <svg style={svgStyle}> <use xlinkHref="#square_o" /> </svg> ), check: ( <svg style={svgStyle}> <use xlinkHref="#check_square_o" /> </svg> ), halfCheck: ( <svg style={halfSvgStyle}> <use xlinkHref="#check_square_o" /> </svg> ), leaf: ( <svg style={svgStyle}> <use xlinkHref="#file_o" /> </svg> ), expandClose: ( <svg style={svgStyle}> <use xlinkHref="#chevron_right" /> </svg> ), expandOpen: ( <svg style={svgStyle}> <use xlinkHref="#chevron_down" /> </svg> ), parentClose: ( <svg style={svgStyle}> <use xlinkHref="#folder_o" /> </svg> ), parentOpen: ( <svg style={svgStyle}> <use xlinkHref="#folder_open_o" /> </svg> ), }} nodes={nestedItems} onCheck={this.handleChecked.bind(this)} onExpand={this.handleExpanded.bind(this)} /> </div> </form> ); return <div>{form}</div>; } } TilesetFinder.propTypes = { datatype: PropTypes.string, orientation: PropTypes.string, onDoubleClick: PropTypes.func, pubSub: PropTypes.object.isRequired, selectedTilesetChanged: PropTypes.func, trackSourceServers: PropTypes.array, }; export default withPubSub(TilesetFinder);
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsInferred.js
mroch/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
sms_sponsorship/webapp/src/components/Message.js
maxime-beck/compassion-modules
import React from 'react'; export default class extends React.Component { render() { let styles = { loadingContainer: { verticalAlign: 'middle', marginTop: '120px', textAlign: 'center' }, loadingTextContainer: { width: '80%', textAlign: 'center', margin: 'auto' }, }; return ( <div style={styles.loadingContainer}> <div style={styles.loadingTextContainer} dangerouslySetInnerHTML={{__html: this.props.text}}/> </div> ) } }
src/layouts/index.js
H3yfinn/finbarmaunsell.com
import React from 'react' import PropTypes from 'prop-types' import Link from 'gatsby-link' import Helmet from 'react-helmet' import './index.css' const Header = () => ( <div style={{ background: '#2452c2', marginBottom: '1.45rem', }} > <div style={{ display: '-ms-flexbox', display: 'flex', flexDirection: 'row', margin: '0 auto', maxWidth: 1200, padding: '1.45rem 1.0875rem', }} > <h1 style={{ paddingTop: '10px', flex: 1, margin: 0 }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > Finn </Link> </h1> <h3 className='' style={{ paddingTop: '20px' }} > <Link className='navLink' to="/about" style={{ paddingLeft: '20px', float: 'right', color: 'white', textDecoration: 'none', }} > About </Link> <Link className='navLink' to="/resume" style={{ paddingLeft: '20px', float: 'right', color: 'white', textDecoration: 'none', }} > Resume </Link> <Link className='navLink' to="/books" style={{ paddingLeft: '20px', float: 'right', color: 'white', textDecoration: 'none', }} > Bookshelf </Link> </h3> </div> </div> ) const TemplateWrapper = ({ children }) => ( <div> <Helmet title="Finbar Maunsell" meta={[ { name: 'description', content: 'Personal website' }, { name: 'keywords', content: 'personal, website, blog' }, ]} /> <Header /> <div style={{ margin: '0 auto', maxWidth: 960, padding: '0px 1.0875rem 1.45rem', paddingTop: '20px', }} > {children()} </div> </div> ) TemplateWrapper.propTypes = { children: PropTypes.func, } export default TemplateWrapper
src/components/EditCheckInItem/messages.links.js
transitlinks/web-app
import React from 'react'; import { defineMessages } from 'react-intl'; export default defineMessages({ 'links-title': { id: 'account.links.linksTitle', defaultMessage: 'User links', description: 'User links' } });
src/svg-icons/action/track-changes.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrackChanges = (props) => ( <SvgIcon {...props}> <path d="M19.07 4.93l-1.41 1.41C19.1 7.79 20 9.79 20 12c0 4.42-3.58 8-8 8s-8-3.58-8-8c0-4.08 3.05-7.44 7-7.93v2.02C8.16 6.57 6 9.03 6 12c0 3.31 2.69 6 6 6s6-2.69 6-6c0-1.66-.67-3.16-1.76-4.24l-1.41 1.41C15.55 9.9 16 10.9 16 12c0 2.21-1.79 4-4 4s-4-1.79-4-4c0-1.86 1.28-3.41 3-3.86v2.14c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V2h-1C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10c0-2.76-1.12-5.26-2.93-7.07z"/> </SvgIcon> ); ActionTrackChanges = pure(ActionTrackChanges); ActionTrackChanges.displayName = 'ActionTrackChanges'; ActionTrackChanges.muiName = 'SvgIcon'; export default ActionTrackChanges;
frontend/src/components/controls/SidebarUI/index.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { dispatchEvent, inStorage, getStorage, setStorage } from 'helpers/utils'; import Resizable from 'components/Resizable'; import './style.scss'; class SidebarUI extends Component { static propTypes = { children: PropTypes.node, defaultExpanded: PropTypes.bool, expanded: PropTypes.bool, resizing: PropTypes.bool, setSidebarResizing: PropTypes.func, storageKey: PropTypes.string, toggleSidebar: PropTypes.func }; static defaultProps = { defaultExpanded: true, storageKey: 'sidebarDisplay' }; constructor(props) { super(props); this.closedWidth = 1; this.state = { initTimeout: false }; } componentDidMount() { const { defaultExpanded, storageKey, toggleSidebar } = this.props; let expanded = defaultExpanded; if (inStorage(storageKey)) { try { expanded = JSON.parse(getStorage(storageKey)); } catch (e) { console.log(`Wrong '${storageKey}' storage value`); } } toggleSidebar(expanded); // allow Resizable to retreive stored width before animating setTimeout(() => this.setState({ initTimeout: true }), 100); } componentDidUpdate(prevProps) { const { expanded, storageKey } = this.props; if (prevProps.expanded !== expanded) { setStorage(storageKey, expanded); dispatchEvent('resize'); } } render() { const { children, expanded, resizing, storageKey } = this.props; const { initTimeout } = this.state; const classes = classNames('wr-sidebar', { animate: initTimeout && !resizing, expanded }); return ( <Resizable classes={classes} flexGrow={0} resizeState={this.props.setSidebarResizing} storageKey={`${storageKey}Width`} overrideWidth={!expanded && this.closedWidth} minWidth={175}> <div className="wr-sidebar-stretch"> { expanded && children } </div> </Resizable> ); } } export default SidebarUI;
packages/ringcentral-widgets-docs/src/app/pages/Components/AlertDisplay/Demo.js
u9520107/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import AlertDisplay from 'ringcentral-widgets/components/AlertDisplay'; import styles from './styles.scss'; const props = {}; props.dismiss = () => null; props.currentLocale = 'en-US'; props.messages = [ { id: '111', level: 'success', message: 'success message', }, { id: '222', level: 'info', message: 'info message', },{ id: '333', level: 'warning', message: 'warning message', }, { id: '444', level: 'danger', message: 'danger', } ]; // eslint-disable-next-line function MessageRender({ message }) { return ( <span>{ message.message }</span> ); } props.getRenderer = () => MessageRender; /** * A example of `AlertDisplay` */ const AlertDisplayDemo = () => ( <div className={styles.root}> <AlertDisplay messages={props.messages} {...props} /> </div> ); export default AlertDisplayDemo;
js/components/deckswiper/index.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Image, View } from 'react-native'; import { Container, Header, Title, Button, IconNB, DeckSwiper, Card, CardItem, Icon, Thumbnail, Text, Left, Right, Body, Content } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; const cardOne = require('../../../img/swiper-1.png'); const cardTwo = require('../../../img/swiper-2.png'); const cardThree = require('../../../img/swiper-3.png'); const cardFour = require('../../../img/swiper-4.png'); const cards = [ { text: 'Card One', name: 'One', image: cardOne, }, { text: 'Card Two', name: 'Two', image: cardTwo, }, { text: 'Card Three', name: 'Three', image: cardThree, }, { text: 'Card Four', name: 'Four', image: cardFour, }, ]; class NHDeckSwiper extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={this.props.openDrawer}> <Icon name="menu" /> </Button> </Left> <Body> <Title>Deck Swiper</Title> </Body> <Right /> </Header> <View style={{ flex: 1, padding: 12 }}> <DeckSwiper dataSource={cards} renderItem={item => <Card style={{ elevation: 3 }}> <CardItem> <Left> <Thumbnail source={item.image} /> <Body> <Text>{item.text}</Text> <Text note>NativeBase</Text> </Body> </Left> </CardItem> <CardItem cardBody> <Image style={{ resizeMode: 'cover', width: null, flex: 1, height: 300 }} source={item.image} /> </CardItem> <CardItem> <IconNB name={'ios-heart'} style={{ color: '#ED4A6A' }} /> <Text>{item.name}</Text> </CardItem> </Card> } /> </View> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(NHDeckSwiper);
examples/3-complex/src/login/index.js
chikara-chan/react-power
import React from 'react' import { render } from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './components/App' function renderHTML() { render( <AppContainer> <App /> </AppContainer>, document.getElementById('root') ) } renderHTML() if (module.hot) { module.hot.accept('./components/App', () => { renderHTML() }) }
app/components/IssueIcon/index.js
Zurico/t7
import React from 'react'; function IssueIcon(props) { return ( <svg height="1em" width="0.875em" className={props.className} > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } IssueIcon.propTypes = { className: React.PropTypes.string, }; export default IssueIcon;
src/Main/PlayerSelecter.js
enragednuke/WoWAnalyzer
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import ReactTooltip from 'react-tooltip'; import { getReport } from 'selectors/report'; import { getCombatants } from 'selectors/combatants'; import PlayerSelectionList from './PlayerSelectionList'; class PlayerSelecter extends Component { static propTypes = { report: PropTypes.shape({ code: PropTypes.string.isRequired, title: PropTypes.string.isRequired, friendlies: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, type: PropTypes.string.isRequired, name: PropTypes.string.isRequired, })), }).isRequired, combatants: PropTypes.array, }; componentWillUnmount() { ReactTooltip.hide(); } render() { const { report, combatants } = this.props; if (!combatants) { return ( <div className="container"> <div> <h1>Fetching players...</h1> <div className="spinner" /> </div> </div> ); } return ( <div className="container"> <h1> <div className="back-button"> <Link to={`/report/${report.code}`} data-tip="Back to fight selection"> <span className="glyphicon glyphicon-chevron-left" aria-hidden="true" /> </Link> </div> Player selection </h1> <div className="panel"> <div className="panel-heading"> <h2>Select the player you wish to analyze</h2> </div> <div className="panel-body" style={{ padding: 0 }}> <PlayerSelectionList /> </div> </div> </div> ); } } const mapStateToProps = state => ({ report: getReport(state), combatants: getCombatants(state), }); export default connect(mapStateToProps)(PlayerSelecter);
entry_types/scrolled/package/spec/frontend/inlineEditing-spec.js
codevise/pageflow
import React from 'react'; import '@testing-library/jest-dom/extend-expect' import {render} from '@testing-library/react' jest.mock('frontend/inlineEditing/components', () => ({ TestDecorator({text, children}) { return <div>{text} Decorator<div>{children}</div></div>; }, TestAlternative({text, children}) { return <div>{text} Alternative</div>; } })); describe('inlineEditing', () => { // Make sure each test imports its own instance of the // frontend/inlineEditing module to reset the internal // collection of loaded inline editing components. beforeEach(() => jest.resetModules()); describe('withInlineEditingDecorator', () => { describe('when inline editing components are loaded', () => { it('wraps component with decorator receiving same props', async () => { const {withInlineEditingDecorator, loadInlineEditingComponents} = await import('frontend/inlineEditing'); const TestComponent = withInlineEditingDecorator('TestDecorator', function TestComponent({text}) { return <div>{text} Test</div>; }); await loadInlineEditingComponents(); const {container} = render(<TestComponent text="Hello" />); expect(container).toHaveTextContent('Hello Decorator'); expect(container).toHaveTextContent('Hello Test'); }) }); describe('when inline editing components are not loaded', () => { it('only renders component', async () => { const {withInlineEditingDecorator} = await import('frontend/inlineEditing'); const TestComponent = withInlineEditingDecorator('TestDecorator', function TestComponent({text}) { return <div>{text} Test</div>; }); const {container} = render(<TestComponent text="Hello" />); expect(container).not.toHaveTextContent('Decorator'); expect(container).toHaveTextContent('Hello Test'); }) }); }); describe('withInlineEditingAlternative', () => { describe('when inline editing components are loaded', () => { it('renders alternative component instead', async () => { const {withInlineEditingAlternative, loadInlineEditingComponents} = await import('frontend/inlineEditing'); const TestComponent = withInlineEditingAlternative('TestAlternative', function TestComponent({text}) { return <div>{text} Test</div>; }); await loadInlineEditingComponents(); const {container} = render(<TestComponent text="Hello" />); expect(container).toHaveTextContent('Hello Alternative'); expect(container).not.toHaveTextContent('Test'); }) }); describe('when inline editing components are not loaded', () => { it('only renders component', async () => { const {withInlineEditingAlternative} = await import('frontend/inlineEditing'); const TestComponent = withInlineEditingAlternative('TestAlternative', function TestComponent({text}) { return <div>{text} Test</div>; }); const {container} = render(<TestComponent text="Hello" />); expect(container).not.toHaveTextContent('Alternative'); expect(container).toHaveTextContent('Hello Test'); }) }); }); });
app/App.js
albybarber/blackpanda
import React from 'react' import Hello from './components/hello/hello' import Grid from './components/grid/grid' // import IconPage from './atoms/icons/docs/IconPage' export default class App extends React.Component { render () { return ( <div> <Hello /> <grid /> </div> ) } }
node_modules/react-bootstrap/es/DropdownToggle.js
chenjic215/search-doctor
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Button from './Button'; import SafeAnchor from './SafeAnchor'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; var propTypes = { noCaret: PropTypes.bool, open: PropTypes.bool, title: PropTypes.string, useAnchor: PropTypes.bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = function (_React$Component) { _inherits(DropdownToggle, _React$Component); function DropdownToggle() { _classCallCheck(this, DropdownToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DropdownToggle.prototype.render = function render() { var _props = this.props, noCaret = _props.noCaret, open = _props.open, useAnchor = _props.useAnchor, bsClass = _props.bsClass, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? SafeAnchor : Button; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return React.createElement( Component, _extends({}, props, { role: 'button', className: classNames(className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && React.createElement('span', { className: 'caret' }) ); }; return DropdownToggle; }(React.Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; export default setBsClass('dropdown-toggle', DropdownToggle);
src/server/html.js
matystl/shopping_list
import React from 'react'; export default class Html extends React.Component { render() { // Only for production. For dev, it's handled by webpack with livereload. const linkStyles = this.props.isProduction && <link href={`/build/app.css?v=${this.props.version}`} rel="stylesheet" />; // TODO: Add favicon. const linkFavicon = false && <link href={`/build/img/favicon.icon?v=${this.props.version}`} rel="shortcut icon" />; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <title>{this.props.title}</title> {linkStyles} {linkFavicon} </head> <body dangerouslySetInnerHTML={{__html: this.props.bodyHtml}} /> </html> ); } } Html.propTypes = { bodyHtml: React.PropTypes.string.isRequired, isProduction: React.PropTypes.bool.isRequired, title: React.PropTypes.string.isRequired, version: React.PropTypes.string.isRequired };
app/routes.js
ayqy/ready-to-work
import React from 'react'; import { Switch, Route } from 'react-router'; import MainPage from './containers/MainPage'; import LoginPage from './containers/LoginPage'; import HistoryPage from './containers/HistoryPage'; import SettingPage from './containers/SettingPage'; export default ( <Switch> <Route exact path="/" component={MainPage} /> <Route exact path="/loggedin" component={MainPage} /> <Route exact path="/login" component={LoginPage} /> <Route exact path="/history" component={HistoryPage} /> <Route exact path="/setting" render={() => <SettingPage/>} /> </Switch> );
src/components/RestaurantList.js
rgdelato/instantly-lunch
import React, { Component } from 'react'; import { TransitionMotion, spring } from 'react-motion'; import RestaurantItem from '../containers/RestaurantItem'; import RestaurantAdd from '../containers/RestaurantAdd'; export default class RestaurantList extends Component { constructor (props) { super(props); this.getStyles = this.getStyles.bind(this); this.willEnterOrLeave = this.willEnterOrLeave.bind(this); } getStyles (restaurants, editing) { return restaurants.reduce((acc, restaurant) => { acc[restaurant.id] = { opacity: spring(1), maxHeight: spring(300), marginBottom: spring(24), borderWidth: 1, padding: spring(12), restaurant, editing }; return acc; }, {}); } willEnterOrLeave (key, style) { return { opacity: spring(0), maxHeight: spring(0), marginBottom: spring(0), borderWidth: 0, padding: spring(0), restaurant: style.restaurant, editing: style.editing }; } render () { const { restaurants, editing } = this.props; return ( <div className="restaurant-list"> <TransitionMotion styles={this.getStyles(restaurants, editing)} willEnter={this.willEnterOrLeave} willLeave={this.willEnterOrLeave} > {(styles) => <div> {Object.keys(styles).map((id) => { const { restaurant, editing, ...style } = styles[id]; return ( <RestaurantItem key={restaurant.id} restaurant={(editing.id === restaurant.id) ? editing : restaurant} editing={editing.id === restaurant.id} style={style} /> ); })} </div> } </TransitionMotion> <RestaurantAdd /> </div> ); } }
src/App.js
michael-lowe-nz/trigMeOnce
import React, { Component } from 'react'; import Main from './components/Main' import Nav from './components/Nav' class App extends Component { render() { return ( <div className="App"> <Nav /> <Main state={this.props.state} dispatch={this.props.dispatch}/> </div> ) } } export default App;
src/containers/DevTools.js
oldsaratov/postcards-spa
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> );
code/workspaces/web-app/src/components/common/buttons/PrimaryActionButton.spec.js
NERC-CEH/datalab
import React from 'react'; import { render } from '@testing-library/react'; import PrimaryActionButton from './PrimaryActionButton'; describe('PrimaryActionButton', () => { it('overrides variant and color props', () => { const props = { variant: 'contained', color: 'secondary' }; expect(render(<PrimaryActionButton {...props}><div>Test Child</div></PrimaryActionButton>).container).toMatchSnapshot(); }); });
examples/03 Nesting/Drag Sources/Container.js
longlho/react-dnd
import React, { Component } from 'react'; import SourceBox from './SourceBox'; import TargetBox from './TargetBox'; import Colors from './Colors'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; @DragDropContext(HTML5Backend) export default class Container extends Component { render() { return ( <div style={{ overflow: 'hidden', clear: 'both', margin: '-.5rem' }}> <div style={{ float: 'left' }}> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW}> <SourceBox color={Colors.YELLOW} /> <SourceBox color={Colors.BLUE} /> </SourceBox> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW} /> </SourceBox> </SourceBox> </div> <div style={{ float: 'left', marginLeft: '5rem', marginTop: '.5rem' }}> <TargetBox /> </div> </div> ); } }
src/js/Root.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Router, Route, applyRouterMiddleware } from 'react-router'; import { useScroll } from 'react-router-scroll'; import App from './App'; import HomePage from './pages/HomePage'; import AnswerUsernamePage from './pages/AnswerUsernamePage'; import ProfessionalProfilePage from './pages/ProfessionalProfilePage'; import ProfessionalProfileIndustryPage from './pages/ProfessionalProfileIndustryPage'; import ProfessionalProfileSkillsPage from './pages/ProfessionalProfileSkillsPage'; import LeisureProfilePage from './pages/LeisureProfilePage'; import LeisureProfileSportsPage from './pages/LeisureProfileSportsPage'; import LeisureProfileHobbiesPage from './pages/LeisureProfileHobbiesPage'; import LeisureProfileGamesPage from './pages/LeisureProfileGamesPage'; import ExplorerProfilePage from './pages/ExplorerProfilePage'; import ExplorerProfileCostPage from './pages/ExplorerProfileCostPage'; import ExplorerProfileEventsPage from './pages/ExplorerProfileEventsPage'; import ExplorerProfileRestaurantsPage from './pages/ExplorerProfileRestaurantsPage'; import ExplorerProfilePlansPage from './pages/ExplorerProfilePlansPage'; import AvailabilityPage from './pages/AvailabilityPage'; import AvailabilityEditOnSignUpPage from './pages/AvailabilityEditOnSignUpPage'; import AvailabilityEditPage from './pages/AvailabilityEditPage'; import ConnectFacebookPage from './pages/ConnectFacebookPage'; import ConnectingFacebookPage from './pages/ConnectingFacebookPage'; import ProposalsPage from './pages/Proposals/Recommendation/ProposalsPage'; import PersonsPage from './pages/PersonsPage'; import PersonsAllPage from './pages/PersonsAllPage'; import PersonsFilterPage from './pages/PersonsFilterPage'; import OwnProposalsPage from './pages/OwnProposalsPage'; import ExplorePage from './pages/ExplorePage'; import ChatThreadsPage from './pages/ChatThreadsPage'; import ChatMessagesPage from './pages/ChatMessagesPage'; import OwnUserInterestsPage from './pages/OwnUser/InterestsPage'; import GalleryPage from './pages/GalleryPage'; import OtherGalleryPage from './pages/OtherGalleryPage'; import GalleryPhotoPage from './pages/GalleryPhotoPage'; import OtherGalleryPhotoPage from './pages/OtherGalleryPhotoPage'; import GalleryProfilePhotoPage from './pages/GalleryProfilePhotoPage'; import GalleryAlbumsPage from './pages/GalleryAlbumsPage'; import GalleryAlbumPhotosPage from './pages/GalleryAlbumPhotosPage'; import QuestionsPage from './pages/QuestionsPage'; import OtherQuestionsPage from './pages/OtherQuestionsPage'; import AnswerQuestionPage from './pages/AnswerQuestionPage'; import AnswerNextQuestionPage from './pages/AnswerNextQuestionPage'; import AnswerNextOtherQuestionPage from './pages/AnswerNextOtherQuestionPage'; import QuestionStatsPage from './pages/QuestionStatsPage'; import QuestionEditedStatsPage from './pages/QuestionEditedStatsPage'; import QuestionOtherStatsPage from './pages/QuestionOtherStatsPage'; import LoginPage from './pages/LoginPage'; import RegisterPage from './pages/RegisterPage'; import RegisterQuestionsLandingPage from './pages/RegisterQuestionLandingPage'; import AnswerUserFieldPage from './pages/AnswerUserFieldPage'; import AnswerProfileFieldPage from './pages/AnswerProfileFieldPage'; import ProfilePage from './pages/ProfilePage'; import DiscoverPage from './pages/DiscoverPage'; import RecommendationPage from './pages/RecommendationPage'; import InvitationsPage from './pages/InvitationsPage'; import ConnectSocialNetworksOnSignUpPage from './pages/ConnectSocialNetworksOnSignUpPage'; import ConnectSocialNetworksPage from './pages/ConnectSocialNetworksPage'; import EditThreadLitePage from './pages/EditThreadLitePage'; import GroupPage from './pages/GroupPage'; import SettingsPage from './pages/SettingsPage'; import RouterActionCreators from './actions/RouterActionCreators'; import LoginStore from './stores/LoginStore'; import ProposalsProjectIntroductionPage from "./pages/Proposals/Project/IntroductionPage"; import ProposalsLeisureIntroductionPage from "./pages/Proposals/Leisure/IntroductionPage"; import ProposalsExperienceIntroductionPage from "./pages/Proposals/Experience/IntroductionPage"; import ProposalBasicEditPage from "./pages/Proposals/Edit/BasicPage"; import ProposalTypeEditPage from "./pages/Proposals/Edit/TypePage"; import ProposalProfessionEditPage from "./pages/Proposals/Edit/ProfessionPage"; import ProposalAvailabilityEditPage from "./pages/Proposals/Edit/AvailabilityPage"; import ProposalAvailabilityDatesEditPage from "./pages/Proposals/Edit/AvailabilityDatesPage"; import ProposalFeaturesPage from "./pages/Proposals/Edit/FeaturesPage"; import ProposalPreviewPage from "./pages/Proposals/Edit/PreviewPage"; import OtherUserProposalsPage from "./pages/OtherUser/ProposalsPage"; import OtherUserAboutMePage from "./pages/OtherUser/AboutMePage"; import OtherUserAnswersPage from "./pages/OtherUser/AnswersPage"; import OtherUserProposalDetailPage from "./pages/OtherUserProposalDetailPage"; import OtherUserInterestsPage from './pages/OtherUser/InterestsPage'; import ProposalDetailPage from "./pages/ProposalDetailPage"; import ProposalDetailMatchesPage from "./pages/ProposalDetailMatchesPage"; import OwnUserAboutMePage from "./pages/OwnUser/AboutMePage"; import OwnUserAnswersPage from "./pages/OwnUser/AnswersPage"; import FriendsPage from "./pages/OwnUser/FriendsPage"; import NetworksPage from "./pages/OwnUser/NetworksPage"; import EditProfilePage from "./pages/OwnUser/EditProfilePage"; function requireAuth(nextState, replaceState) { if (!LoginStore.isLoggedIn()) { let transitionPath = nextState.location.pathname; RouterActionCreators.storeRouterTransitionPath(transitionPath); console.log('Unauthorized path ', transitionPath, ' stored, redirecting to login now...'); replaceState({nextPathname: nextState.location.pathname}, '/') } } export default class Root extends Component { static propTypes = { history: PropTypes.object.isRequired }; render() { const {history} = this.props; return ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route name="home" path="/" component={App}> <Route name="splash" path="/splash" component={HomePage}/> <Route name="answer-username" path="/answer-username" component={AnswerUsernamePage}/> <Route name="professional-profile" path="/professional-profile" component={ProfessionalProfilePage}/> <Route name="professional-profile-industry" path="/professional-profile-industry" component={ProfessionalProfileIndustryPage}/> <Route name="professional-profile-skills" path="/professional-profile-skills" component={ProfessionalProfileSkillsPage}/> <Route name="leisure-profile" path="/leisure-profile" component={LeisureProfilePage}/> <Route name="leisure-profile-sports" path="/leisure-profile-sports" component={LeisureProfileSportsPage}/> <Route name="leisure-profile-hobbies" path="/leisure-profile-hobbies" component={LeisureProfileHobbiesPage}/> <Route name="leisure-profile-games" path="/leisure-profile-games" component={LeisureProfileGamesPage}/> <Route name="explorer-profile" path="/explorer-profile" component={ExplorerProfilePage}/> <Route name="explorer-profile-cost" path="/explorer-profile-cost" component={ExplorerProfileCostPage}/> <Route name="explorer-profile-events" path="/explorer-profile-events" component={ExplorerProfileEventsPage}/> <Route name="explorer-profile-restaurants" path="/explorer-profile-restaurants" component={ExplorerProfileRestaurantsPage}/> <Route name="explorer-profile-plans" path="/explorer-profile-plans" component={ExplorerProfilePlansPage}/> <Route name="availability" path="/availability" component={AvailabilityPage}/> <Route name="availability-edit-on-sign-up" path="/availability-edit-on-sign-up" component={AvailabilityEditOnSignUpPage}/> <Route name="connect-facebook" path="/connect-facebook" component={ConnectFacebookPage}/> <Route name="login" path="/login" component={LoginPage}/> <Route name="register" path="/register" component={RegisterPage}/> <Route onEnter={requireAuth}> <Route name="connecting-facebook" path="/connecting-facebook" component={ConnectingFacebookPage}/> <Route name="proposals" path="/proposals" component={ProposalsPage}/> <Route name="proposals-project-introduction" path="/proposals-project-introduction" component={ProposalsProjectIntroductionPage}/> <Route name="proposals-leisure-introduction" path="/proposals-leisure-introduction" component={ProposalsLeisureIntroductionPage}/> <Route name="proposals-experience-introduction" path="/proposals-experience-introduction" component={ProposalsExperienceIntroductionPage}/> <Route name="proposal-basic-edit" path="/proposal-basic-edit/:proposalId" component={ProposalBasicEditPage}/> <Route name="proposal-basic-create" path="/proposal-basic-edit" component={ProposalBasicEditPage}/> <Route name="proposal-type-edit" path="/proposal-type-edit/:proposalId" component={ProposalTypeEditPage}/> <Route name="proposal-type-create" path="/proposal-type-edit" component={ProposalTypeEditPage}/> <Route name="proposal-profession-edit" path="/proposal-profession-edit/:proposalId" component={ProposalProfessionEditPage}/> <Route name="proposal-profession-create" path="/proposal-profession-edit" component={ProposalProfessionEditPage}/> <Route name="proposal-availability-edit" path="/proposal-availability-edit/:proposalId" component={ProposalAvailabilityEditPage}/> <Route name="proposal-availability-create" path="/proposal-availability-edit" component={ProposalAvailabilityEditPage}/> <Route name="proposal-availability-dates-edit" path="/proposal-availability-dates-edit/:proposalId" component={ProposalAvailabilityDatesEditPage}/> <Route name="proposal-availability-dates-create" path="/proposal-availability-dates-edit" component={ProposalAvailabilityDatesEditPage}/> <Route name="proposal-features-edit" path="/proposal-features-edit/:proposalId" component={ProposalFeaturesPage}/> <Route name="proposal-features-create" path="/proposal-features-edit" component={ProposalFeaturesPage}/> <Route name="proposal-preview-edit" path="/proposal-preview/:proposalId" component={ProposalPreviewPage}/> <Route name="proposal-preview-create" path="/proposal-preview" component={ProposalPreviewPage}/> <Route name="other-user-proposals" path="/p/:slug/proposals" component={OtherUserProposalsPage}/> <Route name="other-user-answers" path="/p/:slug/answers" component={OtherUserAnswersPage}/> <Route name="other-user-interests" path="/p/:slug/interests" component={OtherUserInterestsPage}/> <Route name="other-user-proposal-detail" path="/p/:slug/proposal/:proposalId" component={OtherUserProposalDetailPage}/> <Route name="profile" path="/p/:slug" component={ProfilePage}/> <Route name="own-profile-edit" path="/p/:slug/edit" component={EditProfilePage}/> <Route name="persons" path="/persons" component={PersonsPage}/> <Route name="persons-all" path="/persons-all" component={PersonsAllPage}/> <Route name="persons-filter" path="/persons-filter/:threadId" component={PersonsFilterPage}/> <Route name="friends" path="/friends" component={FriendsPage}/> <Route name="networks" path="/networks" component={NetworksPage}/> <Route name="plans" path="/plans" component={OwnProposalsPage}/> <Route name="proposal-detail" path="/proposal/:proposalId" component={ProposalDetailPage}/> <Route name="proposal-detail-matches" path="/proposal/:proposalId/matches" component={ProposalDetailMatchesPage}/> {/*<Route name="about-me" path="/about-me" component={OwnUserAboutMePage}/>*/} <Route name="answers" path="/answers" component={OwnUserAnswersPage}/> <Route name="availability-edit" path="/availability-edit" component={AvailabilityEditPage}/> {/*<Route name="explore" path="/explore" component={ExplorePage}/>*/} {/*<Route name="register-questions-landing" path="/register-questions-landing" component={RegisterQuestionsLandingPage}/>*/} {/*<Route name="answer-user-fields" path="/answer-user-fields" component={AnswerUserFieldPage}/>*/} {/*<Route name="answer-profile-fields" path="/answer-profile-fields" component={AnswerProfileFieldPage}/>*/} <Route name="notifications" path="/conversations" component={ChatThreadsPage}/> <Route name="messages" path="/p/:slug/conversations" component={ChatMessagesPage}/> <Route name="interests" path="/interests" component={OwnUserInterestsPage}/> {/*<Route name="other-interests" path="/users/:slug/other-interests" component={OtherInterestsPage}/>*/} {/*<Route name="gallery" path="/gallery" component={GalleryPage}/>*/} {/*<Route name="other-gallery" path="/users/:slug/other-gallery/:photoId" component={OtherGalleryPage}/>*/} {/*<Route name="gallery-photo" path="/gallery-photo" component={GalleryPhotoPage}/>*/} {/*<Route name="other-gallery-photo" path="/users/:userId/other-gallery-photo" component={OtherGalleryPhotoPage}/>*/} {/*<Route name="gallery-profile-photo" path="/gallery-profile-photo" component={GalleryProfilePhotoPage}/>*/} {/*<Route name="gallery-albums" path="/gallery-albums" component={GalleryAlbumsPage}/>*/} {/*<Route name="gallery-album-photos" path="/gallery-album-photos" component={GalleryAlbumPhotosPage}/>*/} {/*<Route name="questions" path="/questions" component={QuestionsPage}/>*/} {/*<Route name="other-questions" path="/users/:slug/other-questions" component={OtherQuestionsPage}/>*/} <Route name="answer-question" path="/answer-question/:questionId/:from" component={AnswerQuestionPage}/> <Route name="answer-question-next" path="/answer-question/next" component={AnswerNextQuestionPage}/> <Route name="answer-other-question-next" path="/answer-other-question/:slug/next" component={AnswerNextOtherQuestionPage}/> {/*<Route name="question-stats" path="/question-stats" component={QuestionStatsPage}/>*/} <Route name="question-stats-from" path="/question-stats/:from" component={QuestionEditedStatsPage}/> {/*<Route name="question-stats-other" path="/question-other-stats/:slug" component={QuestionOtherStatsPage}/>*/} {/*<Route name="invitations" path="/invitations" component={InvitationsPage}/>*/} {/*<Route name="discover" path="/discover" component={DiscoverPage}/>*/} {/*<Route name="recommendations" path="/recommendations/:threadId" component={RecommendationPage}/>*/} {/*<Route name="social-networks-on-sign-up" path="/social-networks-on-sign-up" component={ConnectSocialNetworksOnSignUpPage}/>*/} {/*<Route name="social-networks" path="/social-networks" component={ConnectSocialNetworksPage}/>*/} {/*<Route name="edit-thread" path="/edit-thread/:threadId" component={EditThreadLitePage}/>*/} {/*<Route name="groups" path="/badges" component={GroupPage}/>*/} {/*<Route name="group-discover" path="/badges/:groupId/discover" component={DiscoverPage}/>*/} {/*<Route name="group-stats" path="/badges/:groupId" component={GroupStatsPage}/> <Route name="group-members" path="/badges/:groupId/members" component={GroupMembersPage}/> <Route name="group-contents" path="/badges/:groupId/contents" component={GroupContentsPage}/>*/} {/*<Route name="settings" path="/settings" component={SettingsPage}/>*/} </Route> </Route> </Router> ); } }
src/page/Contacts.js
munyrasirio/mss-chat
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, TouchableOpacity, FlatList } from 'react-native'; import { Menu, Name, MenuItem, Contact } from '../component'; import logo from '../img/icon.png'; import avatar2 from '../img/avatar2.jpg'; import avatar1 from '../img/avatar1.jpg'; export default class Contacts extends Component { /*proximo() { this.props.navigation.navigate('chat', {contact: 'Thiago'}) }*/ config() { this.props.navigation.navigate('config') } contact(item) { this.props.navigation.navigate('chat', item) } render() { let data = [] for (var i = 0; i < 10; i++) { data.push({name: 'Guy', source: avatar2, chat: []}); data.push({name: 'Girl', source: avatar1, chat: []}); } return ( <View style={styles.page}> <Menu> <View style={styles.logo}> <Image style={styles.img} source={logo}/> </View> <Name name='MSS Chat'/> <MenuItem name='magnifying-glass' onPress={() => {}}/> <MenuItem name='cog' onPress={this.config.bind(this)}/> </Menu> <View style={styles.contactList}> <FlatList data={data} renderItem={({item, index}) => { return <Contact key={index} source={item.source} name={item.name} date='23:00' lastMessage='Lorem ipsum dolor sit amet.' onPress={() => {this.contact(item)}} /> }} /> </View> </View> ); } } const styles = StyleSheet.create({ page: { flex: 1 }, contactList: { flex: 1, backgroundColor: 'white', flexDirection: 'column' }, //LOGO// logo: { width: 60, alignItems: 'center', justifyContent: 'center', padding: 2 }, img: { flex: 1, resizeMode: 'contain', borderRadius: 150 } });
react-router/components/Routes.js
JonnyCheng/flux-examples
import React from 'react'; import { DefaultRoute, Route } from 'react-router'; import Application from './Application'; import Home from './Home'; import About from './About'; const routes = ( <Route name="app" path="/" handler={Application}> <Route name="about" handler={About}/> <DefaultRoute name="home" handler={Home}/> </Route> ); export default routes;
src/Parser/DeathKnight/Blood/Modules/Features/WastedDeathAndDecay.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import Combatants from 'Parser/Core/Modules/Combatants'; class WastedDeathAndDecay extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, combatants: Combatants, }; CrimsonScourgeProcsCounter = 0; FreeDeathAndDecayCounter = 0; DeathAndDecayCounter = 0; WastedDeathAndDecays = 0; on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DEATH_AND_DECAY.id) { return; } if (this.combatants.selected.hasBuff(SPELLS.CRIMSON_SCOURGE.id, event.timestamp)) { this.FreeDeathAndDecayCounter += 1; } else { this.DeathAndDecayCounter += 1; } } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.CRIMSON_SCOURGE.id) { this.CrimsonScourgeProcsCounter += 1; } } statistic() { this.WastedDeathAndDecays = this.CrimsonScourgeProcsCounter - this.FreeDeathAndDecayCounter; return ( <StatisticBox icon={<SpellIcon id={SPELLS.CRIMSON_SCOURGE.id} />} value={this.WastedDeathAndDecays} label="Wasted Death and Decays" tooltip="You let a Crimson Scourge proc expire without casting Death and Decay." /> ); } statisticOrder = STATISTIC_ORDER.CORE(5); } export default WastedDeathAndDecay;
src/cms/preview-templates/post-preview.js
bapti/blog
// @flow strict import React from 'react'; import type { Entry, WidgetFor } from '../../types'; type Props = { entry: Entry, widgetFor: WidgetFor }; const PostPreview = ({ entry, widgetFor }: Props) => { const body = widgetFor('body'); const title = entry.getIn(['data', 'title']); return ( <div className="post"> <h1 className="post__title">{title}</h1> <div className="post__body">{body}</div> </div> ); }; export default PostPreview;
src/parser/priest/shadow/modules/spells/Dispersion.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import calculateMaxCasts from 'parser/core/calculateMaxCasts'; import Voidform from './Voidform'; const DISPERSION_BASE_CD = 90; const DISPERSION_UPTIME_MS = 6000; class Disperion extends Analyzer { static dependencies = { voidform: Voidform, }; _dispersions = {}; _previousDispersionCast = null; get dispersions() { return Object.keys(this._dispersions).map(key => this._dispersions[key]); } startDispersion(event) { this._dispersions[event.timestamp] = { start: event.timestamp, }; this._previousDispersionCast = event; } endDispersion(event) { this._dispersions[this._previousDispersionCast.timestamp] = { ...this._dispersions[this._previousDispersionCast.timestamp], end: event.timestamp, }; if(this.voidform.inVoidform){ this.voidform.addVoidformEvent(SPELLS.DISPERSION.id, { start: this.voidform.normalizeTimestamp({timestamp: this._previousDispersionCast.timestamp}), end: this.voidform.normalizeTimestamp(event), }); } this._previousDispersionCast = null; } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.DISPERSION.id) this.startDispersion(event); } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.DISPERSION.id) this.endDispersion(event); } suggestions(when) { const dispersionUptime = this.selectedCombatant.getBuffUptime(SPELLS.DISPERSION.id); const maxDispersiontime = Math.floor(calculateMaxCasts(DISPERSION_BASE_CD, this.owner.fightDuration)) * DISPERSION_UPTIME_MS; const dispersedTime = dispersionUptime / this.maxUptime; when(dispersedTime).isGreaterThan(0.20) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You spent {Math.round(dispersionUptime / 1000)} seconds (out of a possible {Math.round(maxDispersiontime / 1000)} seconds) in <SpellLink id={SPELLS.DISPERSION.id} />. Consider using <SpellLink id={SPELLS.DISPERSION.id} /> less or cancel it early.</span>) .icon(SPELLS.DISPERSION.icon) .actual(`${formatPercentage(actual)}% Dispersion uptime`) .recommended(`<${formatPercentage(recommended)}% is recommended, unless the encounter requires it.`) .regular(recommended + 0.05).major(recommended + 0.15); }); } } export default Disperion;
step7-unittest/node_modules/react-router/es6/Lifecycle.js
jintoppy/react-training
'use strict'; import warning from './routerWarning'; import React from 'react'; import invariant from 'invariant'; var object = React.PropTypes.object; /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ var Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount: function componentDidMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : undefined; !this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : undefined; var route = this.props.route || this.context.route; !route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : undefined; this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave); }, componentWillUnmount: function componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute(); } }; export default Lifecycle;
app/pages/resource/resource-header/ResourceHeader.js
fastmonkeys/respa-ui
import PropTypes from 'prop-types'; import React from 'react'; import Button from 'react-bootstrap/lib/Button'; import Grid from 'react-bootstrap/lib/Grid'; import { FormattedNumber } from 'react-intl'; import round from 'lodash/round'; import injectT from '../../../i18n/injectT'; import FavoriteButton from '../../../shared/favorite-button/FavoriteButtonContainer'; import { getPrice, getMaxPeriodText } from '../../../utils/resourceUtils'; import iconHome from '../../../assets/icons/home.svg'; import iconMapMarker from '../../../assets/icons/map-marker.svg'; import iconTicket from '../../../assets/icons/ticket.svg'; import iconUser from '../../../assets/icons/user-o.svg'; import iconClock from '../../../assets/icons/clock-o.svg'; import iconMap from '../../../assets/icons/map.svg'; function ResourceHeader({ onBackClick, onMapClick, isLoggedIn, resource, showBackButton, showMap, unit, t, }) { const formatDistance = (distance) => { if (!distance) { return ''; } const km = distance / 1000; const formattedDistance = km < 10 ? round(km, 1) : round(km); return ( <span> <FormattedNumber value={formattedDistance} /> {' km'} </span> ); }; const peopleCapacityText = t('ResourceCard.peopleCapacity', { people: resource.peopleCapacity }); const maxPeriodText = getMaxPeriodText(t, resource); const priceText = getPrice(t, resource); const typeName = resource.type ? resource.type.name : '\u00A0'; const distance = formatDistance(resource.distance); return ( <section className="app-ResourceHeader"> <Grid> <div className="app-ResourceHeader__content"> {showBackButton && ( <Button bsStyle="link" className="app-ResourceHeader__back-button" onClick={onBackClick} > {t('ResourceHeader.backButton')} </Button> )} <h1>{resource.name}</h1> <div className="app-ResourceHeader__info-wrapper"> <div className="app-ResourceHeader__info"> <img alt={t('ResourceHeader.purpose')} className="app-ResourceHeader__info-icon" src={iconHome} /> <span className="app-ResourceHeader__info-label">{typeName}</span> </div> <div className="app-ResourceHeader__info"> <img alt={t('ResourceHeader.capacity')} className="app-ResourceHeader__info-icon" src={iconUser} /> <span className="app-ResourceHeader__info-label">{peopleCapacityText}</span> </div> <div className="app-ResourceHeader__info"> <img alt={t('ResourceHeader.maxTime')} className="app-ResourceHeader__info-icon" src={iconClock} /> <span className="app-ResourceHeader__info-label">{maxPeriodText}</span> </div> <div className="app-ResourceHeader__info"> <img alt={t('ResourceHeader.price')} className="app-ResourceHeader__info-icon" src={iconTicket} /> <span className="app-ResourceHeader__info-label">{priceText}</span> </div> <div className="app-ResourceHeader__info" id="app-ResourceHeader__info--unit-name"> <img alt={distance ? t('ResourceHeader.distanceAndPremise') : t('ResourceHeader.premise')} className="app-ResourceHeader__info-icon" src={iconMapMarker} /> <span className="app-ResourceHeader__info-label"> {distance} {distance && ', '} {unit.name} </span> </div> <br /> <div className="app-ResourceHeader__buttons"> {!showMap && ( <Button className="app-ResourceHeader__map-button" onClick={onMapClick}> <img alt="" src={iconMap} /> <span>{t('ResourceHeader.mapButton')}</span> </Button> )} {showMap && ( <Button className="app-ResourceHeader__map-button" onClick={onMapClick}> <img alt="" src={iconMap} /> <span>{t('ResourceHeader.resourceButton')}</span> </Button> )} {isLoggedIn && <FavoriteButton resource={resource} />} </div> </div> </div> </Grid> </section> ); } ResourceHeader.propTypes = { isLoggedIn: PropTypes.bool.isRequired, onBackClick: PropTypes.func.isRequired, onMapClick: PropTypes.func.isRequired, resource: PropTypes.object.isRequired, showBackButton: PropTypes.bool.isRequired, showMap: PropTypes.bool.isRequired, t: PropTypes.func.isRequired, unit: PropTypes.object.isRequired, }; ResourceHeader = injectT(ResourceHeader); // eslint-disable-line export default ResourceHeader;
src/components/articles.js
mazairaj/thejulianmaz
import React from 'react'; const Articles = function () { return ( <div style={{ backgroundColor: 'orange', flex: 1 }}> <h1>My Articles</h1> </div> ); }; export default Articles;
client/views/room/contextualBar/RoomFiles/components/FileItemIcon.stories.js
VoiSmart/Rocket.Chat
import React from 'react'; import FileItemIcon from './FileItemIcon'; export default { title: 'room/contextualBar/RoomFiles/FileItemIcon', component: FileItemIcon, }; const options = [ '', 'application/vnd.ms-excel', 'audio', 'video', 'application/msword', 'application/x-zip-compressed', 'application/pdf', ]; export const Default = () => <FileItemIcon type={options[0]} />;
redux/js/todo/containers/RouteVisibleTodoList.js
quiaro/js-playground
import React, { Component } from 'react'; import { connect } from 'react-redux' import { withRouter } from 'react-router'; import * as actions from '../actions/todo' import TodoList from '../components/TodoList' import FetchTodosError from '../components/errors/FetchTodosError' import { getVisibleServerTodos, getIsFetching, getFetchError } from '../reducers/index' class RouteVisibleTodoList extends Component { fetchData() { const { filter, fetchTodos } = this.props; fetchTodos(filter); } componentDidMount() { this.fetchData(); } componentDidUpdate(prevProps) { if (this.props.filter !== prevProps.filter) { this.fetchData(); } } render() { const { serverToggleTodo, todos, errorMessage, isFetching } = this.props; if (isFetching && !todos.length) { return <p>Loading ...</p> } if (errorMessage && !todos.length) { return <FetchTodosError message={errorMessage} onRetry={() => this.fetchData()} /> } return <TodoList todos={todos} onTodoClick={serverToggleTodo} /> } } const mapStateToProps = (state, { params }) => { const filter = params.filter || 'all'; return { todos: getVisibleServerTodos(state, filter), isFetching: getIsFetching(state, filter), errorMessage: getFetchError(state, filter), filter } } RouteVisibleTodoList = withRouter(connect( mapStateToProps, actions )(RouteVisibleTodoList)) export default RouteVisibleTodoList
docs/src/app/components/pages/components/TimePicker/ExampleInternational.js
rhaedes/material-ui
import React from 'react'; import TimePicker from 'material-ui/TimePicker'; const TimePickerInternational = () => ( <div> <TimePicker hintText="Custom Labels" okLabel="确定" cancelLabel="取消" /> </div> ); export default TimePickerInternational;
client/router.js
bmathews/menubar-calendar
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, hashHistory } from 'react-router'; import App from './app.js'; render(( <Router history={hashHistory}> <Route path="/" component={App} /> </Router> ), document.getElementById('react-root'));
js/jqwidgets/demos/react/app/scheduler/resourceswithcustomcolumnwidths/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js'; class App extends React.Component { componentDidMount () { this.refs.myScheduler.ensureAppointmentVisible('id1'); } render () { let appointments = new Array(); let appointment1 = { id: 'id1', description: 'George brings projector for presentations.', location: '', subject: 'Quarterly Project Review Meeting', calendar: 'Room 1', start: new Date(2016, 10, 23, 9, 0, 0), end: new Date(2016, 10, 23, 16, 0, 0) } let appointment2 = { id: 'id2', description: '', location: '', subject: 'IT Group Mtg.', calendar: 'Room 2', start: new Date(2016, 10, 24, 10, 0, 0), end: new Date(2016, 10, 24, 15, 0, 0) } let appointment3 = { id: 'id3', description: '', location: '', subject: 'Course Social Media', calendar: 'Room 1', start: new Date(2016, 10, 27, 11, 0, 0), end: new Date(2016, 10, 27, 13, 0, 0) } let appointment4 = { id: 'id4', description: '', location: '', subject: 'New Projects Planning', calendar: 'Room 2', start: new Date(2016, 10, 23, 0, 0, 0), end: new Date(2016, 10, 25, 23, 59, 59) } let appointment5 = { id: 'id5', description: '', location: '', subject: 'Interview with James', calendar: 'Room 1', start: new Date(2016, 10, 25, 15, 0, 0), end: new Date(2016, 10, 25, 17, 0, 0) } let appointment6 = { id: 'id6', description: '', location: '', subject: 'Interview with Nancy', calendar: 'Room 2', start: new Date(2016, 10, 26, 14, 0, 0), end: new Date(2016, 10, 26, 16, 0, 0) } appointments.push(appointment1); appointments.push(appointment2); appointments.push(appointment3); appointments.push(appointment4); appointments.push(appointment5); appointments.push(appointment6); // prepare the data let source = { dataType: 'array', dataFields: [ { name: 'id', type: 'string' }, { name: 'description', type: 'string' }, { name: 'location', type: 'string' }, { name: 'subject', type: 'string' }, { name: 'calendar', type: 'string' }, { name: 'start', type: 'date' }, { name: 'end', type: 'date' } ], id: 'id', localData: appointments }; let adapter = new $.jqx.dataAdapter(source); let resources = { colorScheme: 'scheme02', dataField: 'calendar', orientation: 'horizontal', resourceColumnWidth: 'auto', source: new $.jqx.dataAdapter(source) }; let appointmentDataFields = { from: 'start', to: 'end', id: 'id', description: 'description', location: 'place', subject: 'subject', resourceId: 'calendar' }; let views = [ 'monthView' ]; return ( <JqxScheduler ref='myScheduler' width={850} height={600} source={adapter} dayNameFormat={'abbr'} date={new $.jqx.date(2016, 11, 23)} showLegend={true} view={0} resources={resources} views={views} appointmentDataFields={appointmentDataFields} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
packages/cf-component-label/example/basic/component.js
jroyal/cf-ui
import React from 'react'; import { Label } from 'cf-component-label'; const LabelComponent = () => ( <p> <Label type="default">Default</Label> <Label type="info">Info</Label> <Label type="success">Success</Label> <Label type="warning">Warning</Label> <Label type="error">Error</Label> </p> ); export default LabelComponent;
src/client/story_box.js
xieyunzi/hacker-menu
import React from 'react' import _ from 'lodash' import Client from 'electron-rpc/client' import StoryList from './story_list.js' import Spinner from './spinner.js' import Menu from './menu.js' import StoryType from '../model/story_type' export default class StoryBox extends React.Component { constructor (props) { super(props) this.client = new Client() this.state = { stories: [], selected: StoryType.TOP_TYPE, status: '', version: '', upgradeVersion: '' } } componentDidMount () { var self = this self.client.request('current-version', function (err, version) { if (err) { console.error(err) return } self.setState({ version: version }) }) self.onNavbarClick(self.state.selected) } onQuitClick () { this.client.request('terminate') } onUrlClick (url) { this.client.request('open-url', { url: url }) } onMarkAsRead (id) { this.client.request('mark-as-read', { id: id }, function () { var story = _.findWhere(this.state.stories, { id: id }) story.hasRead = true this.setState({ stories: this.state.stories }) }.bind(this)) } onNavbarClick (selected) { var self = this self.setState({ stories: [], selected: selected }) self.client.localEventEmitter.removeAllListeners() self.client.on('update-available', function (err, releaseVersion) { if (err) { console.error(err) return } self.setState({ status: 'update-available', upgradeVersion: releaseVersion }) }) var storycb = function (err, storiesMap) { if (err) { return } // console.log(JSON.stringify(Object.keys(storiesMap), null, 2)) var stories = storiesMap[self.state.selected] if (!stories) { return } // console.log(JSON.stringify(stories, null, 2)) self.setState({stories: stories}) } self.client.request(selected, storycb) self.client.on(selected, storycb) } render () { var navNodes = _.map(StoryType.ALL, function (selection) { var className = 'control-item' if (this.state.selected === selection) { className = className + ' active' } return ( <a key={selection} className={className} onClick={this.onNavbarClick.bind(this, selection)}>{selection}</a> ) }, this) var content = null if (_.isEmpty(this.state.stories)) { content = <Spinner /> } else { content = <StoryList stories={this.state.stories} onUrlClick={this.onUrlClick.bind(this)} onMarkAsRead={this.onMarkAsRead.bind(this)} /> } return ( <div className='story-menu'> <header className='bar bar-nav'> <div className='segmented-control'> {navNodes} </div> </header> {content} <Menu onQuitClick={this.onQuitClick.bind(this)} status={this.state.status} version={this.state.version} upgradeVersion={this.state.upgradeVersion} /> </div> ) } }
test/specs/views/Item/ItemImage-test.js
koenvg/Semantic-UI-React
import React from 'react' import ItemImage from 'src/views/Item/ItemImage' import * as common from 'test/specs/commonTests' describe('ItemImage', () => { common.implementsCreateMethod(ItemImage) it('renders Image component', () => { shallow(<ItemImage />) .should.have.descendants('Image') }) it('is wrapped without ui', () => { const wrapper = shallow(<ItemImage />) wrapper.should.have.prop('wrapped', true) wrapper.should.have.prop('ui', false) }) it('has ui with size prop', () => { shallow(<ItemImage size='small' />) .should.have.prop('ui', true) }) })
client/src/javascript/components/general/SortableList.js
stephdewit/flood
import classnames from 'classnames'; import {DragDropContext} from 'react-dnd'; import {injectIntl} from 'react-intl'; import HTML5Backend from 'react-dnd-html5-backend'; import React from 'react'; import SortableListItemDragLayer from './SortableListItemDragLayer'; import SortableListItem from './SortableListItem'; const methodsToBind = ['handleDrop', 'handleMove', 'handleMouseDown']; class SortableList extends React.Component { constructor(props) { super(props); this.sortableListRef = null; this.state = { listOffset: null, items: props.items, }; methodsToBind.forEach(method => { this[method] = this[method].bind(this); }); } static getDerivedStateFromProps(props) { return {items: props.items}; } handleDrop() { if (this.props.onDrop) { this.props.onDrop(this.state.items); } } handleMouseDown(event) { if (this.sortableListRef != null) { this.setState({ listOffset: this.sortableListRef.getBoundingClientRect(), }); } if (this.props.onMouseDown) { this.props.onMouseDown(event); } } handleMove(dragIndex, hoverIndex) { const {items} = this.state; const draggedItem = items[dragIndex]; // Remove the item being dragged. items.splice(dragIndex, 1); // Add the item being dragged in its new position. items.splice(hoverIndex, 0, draggedItem); this.setState({items}); if (this.props.onMove) { this.props.onMove(items); } } getItemList() { const { handleDrop, handleMove, state: {items}, props: {lockedIDs, renderItem}, } = this; return items.map((item, index) => { const {id, visible} = item; return ( <SortableListItem id={id} index={index} isLocked={lockedIDs.includes(id)} isVisible={visible} key={id} onDrop={handleDrop} onMove={handleMove}> {renderItem(item, index)} </SortableListItem> ); }); } render() { const classes = classnames('sortable-list', this.props.className); return ( <ul className={classes} onMouseDown={this.handleMouseDown} ref={ref => { this.sortableListRef = ref; }}> <SortableListItemDragLayer items={this.state.items} listOffset={this.state.listOffset} renderItem={this.props.renderItem} /> {this.getItemList()} </ul> ); } } export default DragDropContext(HTML5Backend)(injectIntl(SortableList));
demo/src/DataTables.js
kiloe/ui
import React from 'react'; import Doc from './Doc'; import View from '../../package/View'; export default class DataTables extends React.Component { //[ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' }, { id: 9, dessert: 'Soggy biscuit', type: 'pastry' } ] // // {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'text'}, // {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'}, render(){ let data = [ { title: 'Numbers, dates and text', state: { selected: [2,4], selectAll: false, page: 1, rowsPerPage: 5, data: Array.apply(0, Array(100)).map( (v,n) => ({ id: n, num: n, square: n*n, cube: n*n*n, date: "2015-12-"+n, date2: "2015-12-"+n, random: Math.floor(Math.random() * 100), text: "Tiramisu chupa chups cupcake cheesecake candy canes cookie. Gingerbread cheesecake topping sweet gingerbread. Muffin tart brownie. Halvah lollipop pastry cake. Muffin marzipan chocolate sweet. Ice cream toffee tootsie roll cookie. Danish chocolate cookie ice cream. Soufflé jelly beans candy gummi bears croissant. Jelly-o bonbon cookie.".substr(n,n).trim() }) ) }, src: Doc.jsx` <DataTable columns={[ {key: 'num', label: 'Number', tip: 'Type: "number"', type:'number'}, {key: 'cube', label: 'Cube ($)', tip: 'Type: "number", format: "$0,0.00"', type: 'number', format: "$0,0.00" }, {key: 'date', label: 'Day of Dec (date)', tip: 'Type: "date", format: "Do MMM"', type: 'date', format: "Do MMM" }, {key: 'date2', label: 'Day of Dec (auto)', tip: 'format: "MMMM D"', format: "MMMM D" }, {key: 'random', label: 'Random', tip: 'Type: "string". A random number between 0 and 100', type: 'string' }, {key: 'text', label: 'Text', tip: 'A string the length of the number', width: '25%'}, ]} onToggleRow={(rowID) => { let selected = this.state.selected.slice(0); if ( selected.indexOf(rowID) < 0 ) selected.push(rowID); //add it please else selected.splice( selected.indexOf(rowID), 1 ); //remove it, yo! this.setState({selected: selected}) }} onSelectAll={(rowIDs) => { if ( this.state.selectAll ) { //Off this.setState({ selectAll: false, selected: (rowIDs.length == this.state.previouslySelected.length ? [] : this.state.previouslySelected ) }); } else { //On this.setState({ selectAll: true, selected: rowIDs, previouslySelected: this.state.selected }); } }} onSort={(colKey) => { let order = ( colKey == this.state.sort && this.state.order == 'asc' ? 'desc' : 'asc' ); this.setState( { page: 1, sort: colKey, order: order, data: this.state.data.slice(0).sort( function( sort, order, a, b ) { return ((a[sort] < b[sort]) ? -1 : (a[sort] > b[sort]) ? 1 : 0) * (order == "desc"?-1:1); }.bind(this,colKey,order) ) } ); }} onPage={(page,rowsPerPage) => { this.setState( { page: page, rowsPerPage: parseInt(rowsPerPage) } ); }} sort={this.state.sort} order={this.state.order} selectAll={this.state.selectAll} data={ this.state.data.slice( (this.state.page-1)*this.state.rowsPerPage, this.state.page*this.state.rowsPerPage ) } selected={this.state.selected} totalRows={this.state.data.length} page={this.state.page} rowsPerPage={this.state.rowsPerPage} rowsPerPageOptions={[5,10,25]} /> `, info:` Testing paging and column types. ` }, { title: 'Editors', state: { page: 1, rowsPerPage: 25, data: Array.apply(0, Array(100)).map( (v,n) => ({ id: n, num: n, type: (n%2).toString(), note: 'Note for #'+n }) ) }, src: Doc.jsx` <DataTable columns={[ {key: 'num', label: 'Number', tip: 'Type: "number"', type:'number'}, {key: 'type', label: 'Type', tip: 'Selector', type: 'number', editor: <Select options={['0','1','2']} /> }, {key: 'note', label: 'Note', tip: 'Text editor', type: 'string', editor: <TextField /> }, ]} onUpdateData={(rowID,colKey,value) => { let data = this.state.data.slice(0); data.forEach( (d,i) => { if ( d.id == rowID ) { d[colKey] = value; data[i] = d; } } ); //XXX: redo this this.setState( { data: data } ); }} onToggleRow={(rowID) => { let selected = this.state.selected.slice(0); if ( selected.indexOf(rowID) < 0 ) selected.push(rowID); //add it please else selected.splice( selected.indexOf(rowID), 1 ); //remove it, yo! this.setState({selected: selected}) }} onSelectAll={(rowIDs) => { if ( this.state.selectAll ) { //Off this.setState({ selectAll: false, selected: (rowIDs.length == this.state.previouslySelected.length ? [] : this.state.previouslySelected ) }); } else { //On this.setState({ selectAll: true, selected: rowIDs, previouslySelected: this.state.selected }); } }} onSort={(colKey) => { let order = ( colKey == this.state.sort && this.state.order == 'asc' ? 'desc' : 'asc' ); this.setState( { page: 1, sort: colKey, order: order, data: this.state.data.slice(0).sort( function( sort, order, a, b ) { return ((a[sort] < b[sort]) ? -1 : (a[sort] > b[sort]) ? 1 : 0) * (order == "desc"?-1:1); }.bind(this,colKey,order) ) } ); }} onPage={(page,rowsPerPage) => { this.setState( { page: page, rowsPerPage: parseInt(rowsPerPage) } ); }} sort={this.state.sort} order={this.state.order} selectAll={this.state.selectAll} data={ this.state.data.slice( (this.state.page-1)*this.state.rowsPerPage, this.state.page*this.state.rowsPerPage ) } selected={this.state.selected} totalRows={this.state.data.length} page={this.state.page} rowsPerPage={this.state.rowsPerPage} /> `, info:` Testing paging and column types. ` }, { title: 'Simple table with no columns config and no row ids', src: Doc.jsx` <DataTable data={ [ { dessert: 'Bakewell tart', type: 'pastry' }, { dessert: 'Chocolate Sundae', type: 'ice cream' } ] } /> `, info:` It still displays but it won't be interactive. ` }, { title: 'No heading row and no checkboxes', src: Doc.jsx` <DataTable columns={[ {key: 'dessert', label: 'Dessert Name', tip: 'yummy name', type:'string'}, {key: 'type', label: 'Type', tip: 'wtf is a dessert type??'}, ]} showHeadings={false} showCheckboxes={false} data={ [ { id: 232, dessert: 'Bakewell tart', type: 'pastry' }, { id: 111, dessert: 'Chocolate Sundae', type: 'ice cream' } ] } selected={ [ 232 ] } /> `, info:` ` }, ]; return ( <View scroll> <View> {data.map((props,i) => <Doc key={i} {...props} />)} </View> </View> ); } }
frontend/app/js/components/rules_v2/edit/addnode.js
serverboards/serverboards
import React from 'react' import i18n from 'app/utils/i18n' function AddNode(props){ const {AddNode, gotoStep, onUpdate, id, section, addNode} = props console.log(props) let input_id="AddNode_"+id.join("_") return ( <div className="ui extend with padding"> <h2 className="ui centered header"> <i className="ui icon plus"/> {i18n("Add an action or condition")} </h2> <div className="separator" style={{height: 40}}/> <div className="ui one narrow column form"> <button className="ui button basic basic teal" onClick={() => addNode("action")}> {i18n("Add action")} </button> <button className="ui button basic basic teal" onClick={() => addNode("condition")}> {i18n("Add condition")} </button> </div> <div className="separator" style={{height: 40}}/> <div className="ui right aligned"> <div className="ui buttons"> <button className="ui button basic" onClick={() => gotoStep("prev", undefined, id)}> {i18n("Previous step")} </button> <button className="ui button basic" onClick={() => gotoStep("next", undefined, id)}> {i18n("Skip step")} </button> </div> </div> </div> ) } export default AddNode
packages/react-scripts/fixtures/kitchensink/src/index.js
gutenye/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
examples/with-webpack-bundle-analyzer/pages/index.js
giacomorebonato/next.js
import React from 'react' import Link from 'next/link' export default class Index extends React.Component { static getInitialProps ({ req }) { if (req) { // Runs only in the server const faker = require('faker') const name = faker.name.findName() return { name } } // Runs only in the client return { name: 'Arunoda' } } render () { const { name } = this.props return ( <div> <h1>Home Page</h1> <p>Welcome, {name}</p> <div> <Link href='/about'><a>About Page</a></Link> </div> </div> ) } }
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/__tests__/Popover.spec.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import { mount } from 'enzyme'; import Popover from '../Popover'; describe('Tooltip', () => { it('should apply popperClassName to popper component', () => { const div = document.createElement('div'); div.setAttribute("id", "tooltip-target"); document.body.appendChild(div); const wrapper = mount( <Popover target="tooltip-target" popperClassName="boba-was-here"> Tooltip Content </Popover>); const tooltipPopoverWrapper = wrapper.find('TooltipPopoverWrapper'); expect(tooltipPopoverWrapper.find({ popperClassName: 'popover show boba-was-here' }).exists()).toBe(true); }); });
examples/todomvc/containers/Root.dev.js
calesce/redux-slider-monitor
import React from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import TodoApp from './TodoApp'; import DevTools from './DevTools'; const Root = ({ store }) => ( <Provider store={store}> <div> <TodoApp /> <DevTools /> </div> </Provider> ); Root.propTypes = { store: PropTypes.object.isRequired }; export default Root;
src/app/containers/SubmitButton.js
pingwing/travel-guide-las-palmas
import React from 'react'; import {Component} from 'react'; export default class SubmitButton extends Component { render() { return ( <button className="submit">Submit</button> ) } }
app/containers/PartnerPage/index.js
openactive/open-sessions
import React from 'react'; import Banner from '../../components/Banner'; import Button from '../../components/Button'; import styles from './styles.css'; export default class PartnerPage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return (<div className={styles.partner}> <Banner> <h1>Become a Partner</h1> <h2>Your gateway to the most popular physical activity finders on the web</h2> </Banner> <section className={styles.section}> <h2>Larger providers & booking system integration</h2> <p>If you already use a booking system, club management system, or similar, then we can connect directly to that system to access the sessions that you want to promote. We're already connected to a number of systems as part of the Openactive community of open data organisations. Please follow the link below to pass us your contact details and we'll be in touch to discuss next steps.</p> <p><Button onClick={() => !(window.location = 'https://www.openactive.io/join.html')}>Leave us your details</Button></p> </section> </div>); } }
src/containers/Home/index.js
hasibsahibzada/quran.com-frontend
import React, { Component } from 'react'; import * as customPropTypes from 'customPropTypes'; import styled from 'styled-components'; import Helmet from 'react-helmet'; import IndexHeader from 'components/IndexHeader'; import cookie from 'react-cookie'; import { asyncConnect } from 'redux-connect'; import { connect } from 'react-redux'; import debug from 'helpers/debug'; import LastVisit from 'components/Home/LastVisit'; import SurahsList from 'components/Home/SurahsList'; import JuzList from 'components/Home/JuzList'; import QuickSurahs from 'components/Home/QuickSurahs'; import LocaleFormattedMessage from 'components/LocaleFormattedMessage'; import Tabs, { Tab } from 'quran-components/lib/Tabs'; import Loader from 'quran-components/lib/Loader'; import { chaptersConnect, juzsConnect } from '../Surah/connect'; export const Title = styled.h4` font-size: 14px; span { margin: 0; line-height: 2; a { padding: 0 15px; } } &:last-child { margin-top: 25px; } `; class Home extends Component { renderJuzList() { const { chapters, juzs } = this.props; if (juzs.loading) { return ( <div className="row"> <Loader isActive relative /> </div> ); } const juzList = Object.values(juzs.entities); return ( <div className="row"> <JuzList chapters={chapters} juzs={juzList.slice(0, 20)} /> <JuzList chapters={chapters} juzs={juzList.slice(20, 28)} /> <JuzList chapters={chapters} juzs={juzList.slice(28, 30)} /> </div> ); } // eslint-disable-next-line class-methods-use-this renderChapterList(chaptersList) { return ( <div className="row"> <SurahsList chapters={chaptersList.slice(0, 38)} /> <SurahsList chapters={chaptersList.slice(38, 76)} /> <SurahsList chapters={chaptersList.slice(76, 114)} /> </div> ); } render() { debug('component:Home', 'Render'); const lastVisit = cookie.load('lastVisit') || null; const { chapters } = this.props; const chaptersList = Object.values(chapters); const chapterTitle = ( <Title className="text-muted"> <LocaleFormattedMessage id="surah.index.heading" defaultMessage="SURAHS (CHAPTERS)" /> </Title> ); const juzTitle = ( <Title className="text-muted"> <LocaleFormattedMessage id="juz.index.heading" defaultMessage="Juz" /> </Title> ); return ( <div className="index-page"> <Helmet title="The Noble Quran - القرآن الكريم" titleTemplate="%s" /> <IndexHeader /> <div className="container"> <div className="row"> <div className="col-md-10 col-md-offset-1"> {lastVisit && ( <LastVisit chapter={chapters[lastVisit.chapterId]} verse={lastVisit.verseId} /> )} <QuickSurahs /> <Tabs> <Tab title={chapterTitle}> {this.renderChapterList(chaptersList)} </Tab> <Tab title={juzTitle}>{this.renderJuzList()}</Tab> </Tabs> </div> </div> </div> </div> ); } } Home.propTypes = { chapters: customPropTypes.chapters.isRequired, juzs: customPropTypes.juzs.isRequired }; const AsyncHome = asyncConnect([ { promise: chaptersConnect }, { promise: juzsConnect } ])(Home); function mapStateToProps(state) { return { chapters: state.chapters.entities, juzs: state.juzs }; } export default connect(mapStateToProps)(AsyncHome);
src/components/Feedback/Feedback.js
lycandjava/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
node_modules/react-bootstrap/es/Checkbox.js
cmccandless/SolRFrontEnd
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: React.PropTypes.bool, disabled: React.PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: React.PropTypes.oneOf(['success', 'warning', 'error']), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Checkbox inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: React.PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Checkbox = function (_React$Component) { _inherits(Checkbox, _React$Component); function Checkbox() { _classCallCheck(this, Checkbox); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Checkbox.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'checkbox', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Checkbox inline>`. To display ' + 'validation state on an inline checkbox, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', null, input, children ) ); }; return Checkbox; }(React.Component); Checkbox.propTypes = propTypes; Checkbox.defaultProps = defaultProps; export default bsClass('checkbox', Checkbox);
src/icons/GlyphCalendar.js
ipfs/webui
import React from 'react' const GlyphCalendar = props => ( <svg viewBox='0 0 100 100' {...props}> <path d='M73.09 22.24h-5.43v-1.69a3.8 3.8 0 0 0-7.59 0v1.69H39.93v-1.69a3.8 3.8 0 0 0-7.59 0v1.69h-5.43a6.65 6.65 0 0 0-6.64 6.64v47.71a6.66 6.66 0 0 0 6.64 6.65h46.18a6.66 6.66 0 0 0 6.64-6.65V28.88a6.65 6.65 0 0 0-6.64-6.64zM25.53 44h48.94v32.59A1.38 1.38 0 0 1 73.09 78H26.91a1.38 1.38 0 0 1-1.38-1.38z' /> </svg> ) export default GlyphCalendar
Libraries/Image/ImageBackground.js
Guardiannw/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ImageBackground * @flow * @format */ 'use strict'; const Image = require('Image'); const React = require('React'); const View = require('View'); /** * Very simple drop-in replacement for <Image> which supports nesting views. * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, ImageBackground, Text } from 'react-native'; * * class DisplayAnImageBackground extends Component { * render() { * return ( * <ImageBackground * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} * > * <Text>React</Text> * </ImageBackground> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('DisplayAnImageBackground', () => DisplayAnImageBackground); * ``` */ class ImageBackground extends React.Component { render() { const {children, style, imageStyle, imageRef, ...props} = this.props; return ( <View style={style}> <Image {...props} style={[ { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, // Temporary Workaround: // Current (imperfect yet) implementation of <Image> overwrites width and height styles // (which is not quite correct), and these styles conflict with explicitly set styles // of <ImageBackground> and with our internal layout model here. // So, we have to proxy/reapply these styles explicitly for actual <Image> component. // This workaround should be removed after implementing proper support of // intrinsic content size of the <Image>. width: style.width, height: style.height, }, imageStyle, ]} ref={imageRef} /> {children} </View> ); } } module.exports = ImageBackground;
src/docs/components/chart/MarkerDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Chart, { Base, Marker, Layers } from 'grommet/components/chart/Chart'; import Anchor from 'grommet/components/Anchor'; import DocsArticle from '../../../components/DocsArticle'; import BackControl from './BackControl'; export default class MarkerDoc extends Component { render () { return ( <DocsArticle context={<BackControl />} title='Marker'> <section> <p>An simple line graphic in a <Anchor path={`/docs/chart`}> Chart</Anchor>. It is typically used to indicate a threshold or to indicate the currently active index the user is hovering over. The location of the line should be specified either via the <code>count</code> and <code>index</code> properties or via the <code>min</code>, <code>max</code>, and <code>value</code> properties. It should be placed inside a <Anchor path={`/docs/chart-layers`}> Layers</Anchor> component. There can be multiple Marker components in the Chart.</p> <Chart> <Base height='small' /> <Layers> <Marker count={5} index={2} vertical={true} /> </Layers> </Chart> </section> <section> <h2>Properties</h2> <dl> <dt><code>colorIndex {'{category}-{index}'}</code></dt> <dd>The color identifier to use for the line color. For example: <code>'graph-2'</code></dd> <dt><code>count {'{number}'}</code></dt> <dd>The number of slots, including both ends. Use this in conjunction with <code>index</code>.</dd> <dt><code>index {'{number}'}</code></dt> <dd>The slot selected. Use this in conjunction with <code>count</code>.</dd> <dt><code>max {'{number}'}</code></dt> <dd>The largest possible value. Defaults to 100.</dd> <dt><code>min {'{number}'}</code></dt> <dd>The smallest possible value. Defaults to 0.</dd> <dt><code>reverse true|false</code></dt> <dd>When true, the indexes count right to left or bottom to top.</dd> <dt><code>value {'{number}'}</code></dt> <dd>The value selected. Use in conjunction with <code>min</code> and <code>max</code>.</dd> <dt><code>vertical true|false</code></dt> <dd>Whether the slots should be layed out horizontally or vertically.</dd> </dl> </section> </DocsArticle> ); } };
src/components/common/alert.js
lq782655835/ReactDemo
import React from 'react'; import { Modal, Alert } from 'antd'; import OrderDetail from '../isdbooking/components/orderdetail'; let QRCode = require('qrcode.react'); class CtripAlert { constructor(){ } show(title='this is title', content='this is content'){ this.showModelLayer(title, content); } showWinXin(account='HH18721845451'){//微信咨询 this.showModelLayer('1对1专属服务',<WeiXin account={account} />); } showComplaint(){//申诉 this.showModelLayer('感谢使用',<Complaint />, 'success', '确定'); } showQRcode(localURL){//生成二维码 this.show('邀请好友扫一扫分享给TA',<QRcode url={localURL}/>); } showStoreLocation(storename='良华购物中心便捷点'){//地点 this.show(storename, <StoreLocation />); } showOrderDetail(){ this.show('费用明细', <OrderDetail />); } showCitySelect(){ let citylist = [{city:'上海', checked:true}, {city:'深圳', checked:false},{city:'北京', checked:false}]; this.showModelLayer('请选择用车城市', <CitySelect citylist={citylist}/>, 'info','确定'); } showTelphone(){ this.showModelLayer('确定拨打客服热线?','','confirm', '确定', '取消'); } showModelLayer = (title = 'title', content = 'content', type='info', okText='知道了', cancelText='取消', okCallBack, cancelCallBack) =>{ //type:info success error warning confirm Modal[type]({ okText:okText, cancelText:cancelText, title: title, content: content, onOk() { if(okCallBack) okCallBack(); }, onCancel(){ if(cancelCallBack) cancelCallBack(); } }); } } class QRcode extends React.Component{ render(){ let { url } = this.props; return ( <div className='qrcode'> <QRCode level='L' value={url}/> </div> ); } } class WeiXin extends React.Component{ render(){ let { account } = this.props; return ( <div> <p>长按微信号<span className='weixin'>{account}</span> 拷贝,微信中粘贴添加好友</p> <p>服务时间:工作日 9:00-18:00</p> </div> ); } } class Complaint extends React.Component{ render(){ return ( <div> <p>已收到您的申诉请求,稍后会有客服人员为您服务</p> </div> ); } } class StoreLocation extends React.Component{ render(){ return ( <div> <p>门店电话:021-62338565</p> <p>营业时间:08:00-21:00</p> <p>地址:申滨路990号(申滨路宁虹路交叉口)</p> </div> ); } } class CitySelect extends React.Component{ render(){ let {citylist} = this.props; return ( <div className='cityselect'> { citylist.map((item,index) =>{ let {city, checked} = item; let icon = checked ? 'success' : 'info'; return <Alert message={city} type={icon} key={index} showIcon className='pointer'/> }) } </div> ); } } export default new CtripAlert();
src/svg-icons/content/clear.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentClear = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); ContentClear = pure(ContentClear); ContentClear.displayName = 'ContentClear'; ContentClear.muiName = 'SvgIcon'; export default ContentClear;
src/svg-icons/action/flight-takeoff.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFlightTakeoff = (props) => ( <SvgIcon {...props}> <path d="M2.5 19h19v2h-19zm19.57-9.36c-.21-.8-1.04-1.28-1.84-1.06L14.92 10l-6.9-6.43-1.93.51 4.14 7.17-4.97 1.33-1.97-1.54-1.45.39 1.82 3.16.77 1.33 1.6-.43 5.31-1.42 4.35-1.16L21 11.49c.81-.23 1.28-1.05 1.07-1.85z"/> </SvgIcon> ); ActionFlightTakeoff = pure(ActionFlightTakeoff); ActionFlightTakeoff.displayName = 'ActionFlightTakeoff'; ActionFlightTakeoff.muiName = 'SvgIcon'; export default ActionFlightTakeoff;
examples/todomvc-react/src/index.js
Anaphalis/ds
import React from 'react' import { render } from 'react-dom' import App from './containers/App' import 'todomvc-app-css/index.css' render( <App />, document.getElementById('root') )
src/@ui/RelatedContent/RelatedContentWithoutData.js
NewSpring/Apollos
import React from 'react'; import { View } from 'react-native'; import PropTypes from 'prop-types'; import { compose, pure, setPropTypes, defaultProps, branch, withProps } from 'recompose'; import { times } from 'lodash'; import { Link } from '@ui/NativeWebRouter'; import { getLinkPath, getItemImages } from '@utils/content'; import { withThemeMixin } from '@ui/theme'; import styled from '@ui/styled'; import { H5 } from '@ui/typography'; import ThumbnailCard from '@ui/ThumbnailCard'; import ErrorCard from '@ui/ErrorCard'; const generateLoadingStateData = (numberOfItems = 1) => { const itemData = () => ({ id: 'fakeId0', title: '', channelName: '', content: { images: [], }, isLoading: true, }); const loadingStateData = []; times(numberOfItems, (n) => { const newData = itemData(); newData.id = `fakeId${n}`; loadingStateData.push(newData); }); return loadingStateData; }; const enhance = compose( pure, setPropTypes({ content: PropTypes.array, sectionTitle: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), renderItem: PropTypes.func, isLoading: PropTypes.bool, }), defaultProps({ isLoading: false, sectionTitle: 'More Like This', content: [], }), branch(({ isLoading, content }) => (isLoading && !content.length), withProps({ content: generateLoadingStateData(3), })), withThemeMixin(() => ({ type: 'light', })), ); const defaultItemRenderer = item => ( <Link to={getLinkPath(item)} key={item.id}> <ThumbnailCard title={item.title || item.name || ''} category={item.category} images={getItemImages(item)} isLoading={item.isLoading} /> </Link> ); const renderSectionTitle = (sectionTitle) => { if (typeof sectionTitle !== 'string') return sectionTitle; return (<Title>{sectionTitle}</Title>); }; const Wrapper = styled(({ theme }) => ({ paddingVertical: theme.sizing.baseUnit, backgroundColor: theme.colors.lightSecondary, }))(View); const Title = styled(({ theme }) => ({ textAlign: 'center', marginBottom: theme.sizing.baseUnit / 2, paddingHorizontal: theme.sizing.baseUnit, }))(H5); const RelatedContentWithoutData = enhance(({ sectionTitle, renderItem = defaultItemRenderer, content, error, style, }) => ( <Wrapper style={style}> {sectionTitle ? renderSectionTitle(sectionTitle) : null} {error ? <ErrorCard error={error} /> : null} {(content || []).map(renderItem)} </Wrapper> )); export default RelatedContentWithoutData;
__tests__/index.android.js
atixlabs/atm-mobileapp
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/index.js
tobias2801/app_gestoria
import './sass/main.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import Main from './MainComposition'; let elemToRender = document.querySelector('#main-container'); ReactDOM.render( <Main />, elemToRender );
source/containers/Accounts.js
mpalmer685/DebtPayoffCalculator
import React from 'react' import { Grid, Row, Col } from 'react-bootstrap' import { connect } from 'react-redux' import Account from 'models/Account' import validateAccount from 'models/AccountFormValidation' import { updateForm, resetForm, addAccount, deleteAccount } from 'actions/AccountActionCreators' import { AccountCreationForm, AccountList } from 'components/Accounts' function formIsValid({ name, interestRate, balance, minimumPayment }) { return !name && !interestRate && !balance && !minimumPayment } class Accounts extends React.Component { constructor() { super() this.state = { formValidation: {} } this.handleFormUpdate = this.handleFormUpdate.bind(this) this.handleResetForm = this.handleResetForm.bind(this) this.handleFormSubmit = this.handleFormSubmit.bind(this) this.handleRemoveAccount = this.handleRemoveAccount.bind(this) } handleFormUpdate(key, event) { this.props.updateForm(key, event.target.value) } handleResetForm() { this.props.resetForm() } handleFormSubmit() { const formValidation = validateAccount(this.props.currentFormAccount) this.setState({ formValidation }) if (formIsValid(formValidation)) { this.props.addAccount(this.props.currentFormAccount) } } handleRemoveAccount(accountId) { this.props.deleteAccount(accountId) } render() { return ( <Grid> <Row> <Col md={6}> <AccountList accounts={this.props.accounts} onRemoveAccount={this.handleRemoveAccount}/> </Col> <Col md={5} mdOffset={1}> <AccountCreationForm account={this.props.currentFormAccount} formValidation={this.state.formValidation} onFormUpdate={this.handleFormUpdate} onFormReset={this.handleResetForm} onFormSubmit={this.handleFormSubmit}/> </Col> </Row> </Grid> ) } } Accounts.propTypes = { accounts: React.PropTypes.array.isRequired, currentFormAccount: React.PropTypes.instanceOf(Account).isRequired, updateForm: React.PropTypes.func.isRequired, resetForm: React.PropTypes.func.isRequired, addAccount: React.PropTypes.func.isRequired, deleteAccount: React.PropTypes.func.isRequired } function mapStateToProps(state) { return { accounts: state.accounts || [], currentFormAccount: state.currentFormAccount } } export default connect( mapStateToProps, { updateForm, resetForm, addAccount, deleteAccount } )(Accounts)
src/components/__tests__/general/error-test.js
elarasu/roverz-chat
/** * Test to check if the component renders correctly */ /* global it expect */ import { Alert } from 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import Error from '@components/general/Error'; it('Error renders correctly', () => { const tree = renderer.create( <Error text={'We can\'t find that'} />, ).toJSON(); expect(tree).toMatchSnapshot(); }); it('Error w/ Try Again Button renders correctly', () => { const tree = renderer.create( <Error tryAgain={() => { Alert.alert('Hey there'); }} />, ).toJSON(); expect(tree).toMatchSnapshot(); });
examples/star-wars/js/app.js
SBUtltmedia/relay
/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import StarWarsApp from './components/StarWarsApp'; import StarWarsAppHomeRoute from './routes/StarWarsAppHomeRoute'; ReactDOM.render( <Relay.RootContainer Component={StarWarsApp} route={new StarWarsAppHomeRoute({ factionNames: ['empire', 'rebels'], })} />, document.getElementById('root') );
src/app/components/forms/editors/Summernote.js
backpackcoder/world-in-flames
import React from 'react' import 'script-loader!summernote/dist/summernote.min.js' export default class Summernote extends React.Component { componentDidMount() { $(this.refs.editor).summernote({ height: this.props.height || 270 }) } componentWillUnmount() { $(this.refs.editor).summernote('destroy'); } render() { const {children, ...props} = this.props; return ( <div {...props} ref="editor"> {children} </div> ) } }
src/js/About.js
vincentleung1/PersonalPage
import React, { Component } from 'react'; import '../css/ContentStyle.css'; class About extends Component { render() { return ( <div className="content-body"> <h1 className="title"> About me </h1> <div className="about"> <p> I am a new Software Engineering (B.ASc) graduate. I love the tech industry for what and where it has brought me. Whether it is fixing computers or developing software, both push me forward into a future of technology. </p> <p> Aside from technology, I enjoy playing video games, snowboarding, and playing badminton on a weekly basis. As a side gig, I do some home renovations, such as walls and flooring. </p> </div> </div> ); } } export default About;
src/components/AboutPage.spec.js
rafurr/react-material-ui-components
import React from 'react'; import {shallow} from 'enzyme'; import {expect} from 'chai'; import AboutPage from './AboutPage'; describe('<AboutPage />', () => { it('should have a header called \'About\'', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.find('h2').text(); const expected = 'About'; expect(actual).to.equal(expected); }); it('should have a header with \'alt-header\' class', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.find('h2').prop('className'); const expected = 'alt-header'; expect(actual).to.equal(expected); }); it('should link to an unknown route path', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.findWhere(n => n.prop('to') === '/badlink').length; const expected = 1; expect(actual).to.be.equal(expected); }); });
src/layouts/CoreLayout/CoreLayout.js
weixing2014/iTodo
import React from 'react' import Header from '../../components/Header' import classes from './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className={classes.mainContainer}> {children} </div> </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
blueocean-material-icons/src/js/components/svg-icons/device/battery-charging-full.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const DeviceBatteryChargingFull = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/> </SvgIcon> ); DeviceBatteryChargingFull.displayName = 'DeviceBatteryChargingFull'; DeviceBatteryChargingFull.muiName = 'SvgIcon'; export default DeviceBatteryChargingFull;
test/helpers/shallowRenderHelper.js
harrydu2014/gallery-by-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
src/__tests__/LoadProgressBar.spec.js
video-react/video-react
import React from 'react'; import { shallow, mount } from 'enzyme'; import LoadProgressBar from '../components/control-bar/LoadProgressBar'; describe('LoadProgressBar', () => { it('should render with "div" tag', () => { const wrapper = mount( <LoadProgressBar buffered={{ length: 1, start: () => {}, end: () => {} }} duration={1000} /> ); expect(wrapper.find('div.video-react-load-progress').length).toBe(1); }); it('should render with "video-react-load-progress" class', () => { const wrapper = shallow( <LoadProgressBar buffered={{ length: 1, start: () => {}, end: () => {} }} duration={1000} /> ); expect(wrapper.hasClass('video-react-load-progress')).toBe(true); }); it('should render children when passed in', () => { const wrapper = shallow( <LoadProgressBar buffered={{ length: 1, start: () => {}, end: () => {} }} duration={1000} /> ); expect(wrapper.children().length).toBeGreaterThan(0); }); });
js/components/App/index.js
mxstbr/postcss.parts
import React, { Component } from 'react'; import withRouter from 'react-router/lib/withRouter'; import { connect } from 'react-redux'; import Wrapper from './Wrapper'; import Header from '../Header'; import PluginList from '../PluginList'; import SearchField from '../SearchField'; import ListHeading from '../ListHeading'; import { loadPlugins } from '../../actions'; import getTag from '../../utils/url'; import capitalize from '../../utils/capitalize'; class App extends Component { constructor() { super(); this.handleSearch = this.handleSearch.bind(this); } componentDidMount() { this.props.loadPlugins(); } handleSearch(evt) { const { location: { pathname , query: { searchTerm }} } = this.props; //Create one history slot for having a query so the back button will remove the query const action = searchTerm ? 'replace' : 'push'; this.props.router[action](`${pathname}?searchTerm=${evt.target.value}`) } render() { const { children, location: { query: { searchTerm }, pathname } } = this.props; const tag = getTag(pathname); let content = children; if (!tag && searchTerm) { content = <PluginList {...this.props} /> } return( <div> <Header /> <Wrapper> <SearchField value={searchTerm || ""} tag={tag} onChange={this.handleSearch} /> {tag && (<ListHeading key="ListHeading" text={capitalize(tag)}></ListHeading>)} {content} </Wrapper> </div> ); } } const mapDispatchToProps = { loadPlugins }; export default connect(undefined, mapDispatchToProps)(withRouter(App));
src/helpers/__tests__/getDataDependencies-test.js
captainill/react-redux-universal-hot-example
import { expect } from 'chai'; import React from 'react'; import { div } from 'react-dom'; import getDataDependencies from '../getDataDependencies'; describe('getDataDependencies', () => { let getState; let dispatch; let location; let params; let CompWithFetchData; let CompWithNoData; let CompWithFetchDataDeferred; const NullComponent = null; beforeEach(() => { getState = 'getState'; dispatch = 'dispatch'; location = 'location'; params = 'params'; CompWithNoData = () => <div />; CompWithFetchData = () => <div />; CompWithFetchData.fetchData = (_getState, _dispatch, _location, _params) => { return `fetchData ${_getState} ${_dispatch} ${_location} ${_params}`; }; CompWithFetchDataDeferred = () => <div />; CompWithFetchDataDeferred.fetchDataDeferred = (_getState, _dispatch, _location, _params) => { return `fetchDataDeferred ${_getState} ${_dispatch} ${_location} ${_params}`; }; }); it('should get fetchDatas', () => { const deps = getDataDependencies([ NullComponent, CompWithFetchData, CompWithNoData, CompWithFetchDataDeferred ], getState, dispatch, location, params); expect(deps).to.deep.equal([ 'fetchData getState dispatch location params' ]); }); it('should get fetchDataDeferreds', () => { const deps = getDataDependencies([ NullComponent, CompWithFetchData, CompWithNoData, CompWithFetchDataDeferred ], getState, dispatch, location, params, true); expect(deps).to.deep.equal([ 'fetchDataDeferred getState dispatch location params' ]); }); });
node_modules/npm/docs/src/components/seo.js
giovannic/giovannic.github.com
/** * SEO component that queries for data with * Gatsby's useStaticQuery React hook * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' import { useStaticQuery, graphql } from 'gatsby' function SEO ({ description, lang, meta, title }) { const { site } = useStaticQuery( graphql` query { site { siteMetadata { title description author } } } ` ) const metaDescription = description || site.siteMetadata.description return ( <Helmet htmlAttributes={{ lang }} title={title} titleTemplate={`%s | ${site.siteMetadata.title}`} meta={[ { name: 'description', content: metaDescription }, { property: 'og:title', content: title }, { property: 'og:description', content: metaDescription }, { property: 'og:type', content: 'website' }, { name: 'twitter:card', content: 'summary' }, { name: 'twitter:creator', content: site.siteMetadata.author }, { name: 'twitter:title', content: title }, { name: 'twitter:description', content: metaDescription } ].concat(meta)} /> ) } SEO.defaultProps = { lang: 'en', meta: [], description: '' } SEO.propTypes = { description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string.isRequired } export default SEO
code/fluxible-isomorphic/components/ResetButton.js
DJCordhose/react-playground
import React from 'react'; export default class ResetButton extends React.Component { render() { return ( <button onClick={this.props.resetHandler}>Clear </button> ); } }
pootle/static/js/admin/components/Project/ProjectEdit.js
Finntack/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import ProjectForm from './ProjectForm'; const ProjectEdit = React.createClass({ propTypes: { collection: React.PropTypes.object.isRequired, model: React.PropTypes.object, onAdd: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, }, render() { return ( <div className="item-edit"> <div className="hd"> <h2>{gettext('Edit Project')}</h2> <button onClick={this.props.onAdd} className="btn btn-primary" > {gettext('Add Project')} </button> </div> <div className="bd"> {!this.props.model ? <p>{gettext('Use the search form to find the project, ' + 'then click on a project to edit.')}</p> : <ProjectForm key={this.props.model.id} model={this.props.model} collection={this.props.collection} onSuccess={this.props.onSuccess} onDelete={this.props.onDelete} /> } </div> </div> ); }, }); export default ProjectEdit;
node_modules/react-router/es/Router.js
Sweetgrassbuffalo/ReactionSweeGrass-v2
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for putting history on context. */ var Router = function (_React$Component) { _inherits(Router, _React$Component); function Router() { var _temp, _this, _ret; _classCallCheck(this, Router); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { match: _this.computeMatch(_this.props.history.location.pathname) }, _temp), _possibleConstructorReturn(_this, _ret); } Router.prototype.getChildContext = function getChildContext() { return { router: _extends({}, this.context.router, { history: this.props.history, route: { location: this.props.history.location, match: this.state.match } }) }; }; Router.prototype.computeMatch = function computeMatch(pathname) { return { path: '/', url: '/', params: {}, isExact: pathname === '/' }; }; Router.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var _props = this.props, children = _props.children, history = _props.history; invariant(children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element'); // Do this here so we can setState when a <Redirect> changes the // location in componentWillMount. This happens e.g. when doing // server rendering using a <StaticRouter>. this.unlisten = history.listen(function () { _this2.setState({ match: _this2.computeMatch(history.location.pathname) }); }); }; Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { warning(this.props.history === nextProps.history, 'You cannot change <Router history>'); }; Router.prototype.componentWillUnmount = function componentWillUnmount() { this.unlisten(); }; Router.prototype.render = function render() { var children = this.props.children; return children ? React.Children.only(children) : null; }; return Router; }(React.Component); Router.propTypes = { history: PropTypes.object.isRequired, children: PropTypes.node }; Router.contextTypes = { router: PropTypes.object }; Router.childContextTypes = { router: PropTypes.object.isRequired }; export default Router;
src/layouts/CoreLayout/CoreLayout.js
Lily418/Realtime-News-Client
import React from 'react' import Header from '../../components/Header' import './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className='core-layout__viewport'> {children} </div> </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
src/Components/ShowParkingDetailsModal.js
gourie/ParkingPlaza
/* * Author: Joeri Nicolaes * version: alpha */ import React from 'react'; import { Button, Modal } from 'react-bootstrap'; /** * React Component: ShowParkingDetailsModal */ export default class ShowParkingDetailsModal extends React.Component { /** * Standard ES6 method */ constructor(props) { super(props); if (this.props.config.debug==true) { console.log("in ShowParkingDetailsModal/constructor"); } } /** * Standard React method: render */ render() { return ( <Modal show={this.props.show} onHide={this.props.hide.bind(null, 'parking')} > <Modal.Header closeButton> <Modal.Title>Confirm your parking</Modal.Title> </Modal.Header> <Modal.Body> { this.props.loggedIn ? <div> { Object.keys(this.props.availableParkingSlot).length != 0 ? <div> <div className="row"> <div className="col-md-12 col-xs-12"> <p>We have the following parking available for this event:</p> </div> </div> <div className="row"> <div className="col-md-12 col-xs-12"> <p className="text-muted"><strong>Address</strong> {this.props.availableParkingSlot['address']}</p> </div> <div className="col-md-3 col-xs-3"> <p className="text-muted"><strong>Price</strong> {this.props.availableParkingSlot['price']}</p> </div> <div className="col-md-9 col-xs-9"> <p className="text-muted"><strong>Distance to stadium</strong> {this.props.availableParkingSlot['distance']} km</p> </div> <div className="col-md-12 col-xs-12"> <Button onClick={this.props.reserveParking} className="btn btn-primary" id="reservationButton" data-toggle="tooltip" title="Click this button to book your Parking.">Pay</Button> </div> </div> </div> : <div className="row"> <div className="col-md-12 col-xs-12"> <p className="text-muted">Sorry, there is no parking unit available at this time.</p> </div> </div> } </div> : <div className="row"> <p className="text-muted alertmessage"> Please log in first to book a parking. </p> </div> } </Modal.Body> <Modal.Footer> <Button onClick={this.props.hide.bind(null, 'parking')}>Cancel</Button> </Modal.Footer> </Modal> ); } } ShowParkingDetailsModal.propTypes = { config: React.PropTypes.object, show: React.PropTypes.bool, availableParkingSlot: React.PropTypes.object, loggedIn: React.PropTypes.bool, };
src/views/components/RoomsScreen.js
physiii/open-automation
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {compose} from 'redux'; import {Switch, Redirect} from 'react-router-dom'; import {Route, withRoute} from './Route.js'; import NavigationScreen from './NavigationScreen.js'; import List from './List.js'; import BlankState from './BlankState.js'; import ServiceCardGrid from './ServiceCardGrid.js'; import {getDevices} from '../../state/ducks/devices-list/selectors.js'; import {getServices} from '../../state/ducks/services-list/selectors.js'; import {getRooms, hasInitialFetchCompleted} from '../../state/ducks/rooms-list/selectors.js'; export const RoomsScreen = (props) => { return ( <NavigationScreen title="Rooms" url={props.match.urlWithoutOptionalParams} isContextRoot={true}> {props.isLoading ? <span>Loading</span> : <Switch> <Route exact path={props.match.url} render={() => ( <React.Fragment> {!props.rooms.length && <BlankState heading="No Rooms" body="Use ‘Settings’ to add rooms and they will show up here." /> } <List isOrdered={true} renderIfEmpty={false}> {props.rooms.map((room) => ({ key: room.id, label: room.name, link: props.match.url + '/' + room.id }))} </List> </React.Fragment> )} /> <Route path={props.match.url + '/:roomId'} render={(routeProps) => { const room = props.rooms.find((_room) => _room.id === routeProps.match.params.roomId); if (!room) { return <Redirect to={props.match.url} />; } const roomDevices = props.devices.filter((device) => device.room_id === routeProps.match.params.roomId), roomServices = props.services.filter((service) => roomDevices.find((device) => device.id === service.device_id)); return ( <NavigationScreen title={room.name} url={routeProps.match.url}> {!roomServices.size && <BlankState heading="No Devices" body="Use a device’s settings to add it to this room." />} <ServiceCardGrid services={roomServices} /> </NavigationScreen> ); }} /> <Route render={() => <Redirect to={props.match.url} />} /> </Switch>} </NavigationScreen> ); }; RoomsScreen.propTypes = { devices: PropTypes.object.isRequired, services: PropTypes.object.isRequired, rooms: PropTypes.array.isRequired, isLoading: PropTypes.bool, match: PropTypes.object.isRequired }; const mapStateToProps = ({devicesList, servicesList, roomsList}) => ({ devices: getDevices(devicesList, false), services: getServices(servicesList, false), rooms: getRooms(roomsList), isLoading: !hasInitialFetchCompleted(roomsList) }); export default compose( withRoute(), connect(mapStateToProps) )(RoomsScreen);
src/main/app/src/component/DetailView/DetailView.js
p632-sp-2017/microservice-catalog-frontend
import React from 'react'; import './DetailView.css'; import ServiceTable from './ServiceTable' /** * Component to display all fields of a microservice * @param {[type]} serviceDetails [description] */ const DetailView = (serviceDetails) => { let detailHtml = []; let data = serviceDetails; let keys = Object.keys(data); for(let i=0; i<keys.length; i++){ if(data[keys[i]] !== null && !(data[keys[i]] instanceof Array)){ detailHtml.push(<div className="DetailViewRow" key={i}> <div className="fieldKey">{keys[i]}</div> <div className="fieldValue">{data[keys[i]]}</div> </div>); } if(data[keys[i]] instanceof Array) { let tableObj = { keyVal: keys[i], tableData: data[keys[i]] } detailHtml.push(<ServiceTable {...tableObj} />) } } return( <div className="DetailView">{detailHtml}</div> ); } DetailView.displayName = 'DetailView'; export default DetailView;
examples/huge-apps/app.js
levjj/react-router
import React from 'react'; import { Router } from 'react-router'; import stubbedCourses from './stubs/COURSES'; var rootRoute = { component: 'div', childRoutes: [{ path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile'), ] }] }; React.render( <Router routes={rootRoute} />, document.getElementById('example') ); // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like // // import { Route } from 'react-router' // import App from './components/App'; // import Course from './routes/Course/components/Course'; // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar'; // import Announcements from './routes/Course/routes/Announcements/components/Announcements'; // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement'; // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar'; // import Assignments from './routes/Course/routes/Assignments/components/Assignments'; // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment'; // import CourseGrades from './routes/Course/routes/Grades/components/Grades'; // import Calendar from './routes/Calendar/components/Calendar'; // import Grades from './routes/Grades/components/Grades'; // import Messages from './routes/Messages/components/Messages'; // React.render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // );
frontend/test/app/containers/LoadingPage-test.js
mozilla/testpilot
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import LoadingPage from '../../../src/app/containers/LoadingPage'; describe('app/containers/LoadingPage', () => { const subject = shallow(<LoadingPage />); it('should render expected default content', () => { expect(subject.find('div.full-page-wrapper')).to.have.property('length', 1); expect(subject.find('Loading')).to.have.property('length', 1); }); });
src/DetailsSection/CardList/TableBody.js
conferenceradar/list
import React from 'react'; import { ListWrapper } from './styles'; import NoResults from '../NoResults'; const CustomTableBody = ({ rowIds, Row, className }) => ( <ListWrapper> { (!rowIds || rowIds.size === 0) && <NoResults /> } { rowIds && rowIds.map(r => <Row key={r} griddleKey={r} />) } </ListWrapper> ); export default CustomTableBody;
app/javascript/spec/ops-tenant-form/ops-tenant-form.spec.js
ManageIQ/manageiq-ui-classic
import React from 'react'; import { act } from 'react-dom/test-utils'; import fetchMock from 'fetch-mock'; import { mount } from '../helpers/mountForm'; import OpsTenantForm from '../../components/ops-tenant-form/ops-tenant-form'; import MiqFormRenderer from '../../forms/data-driven-form'; import miqRedirectBack from '../../helpers/miq-redirect-back'; import '../helpers/miqSparkle'; import '../helpers/addFlash'; import '../helpers/miqFlashLater'; import '../helpers/sprintf'; describe('OpstTenantForm', () => { let initialProps; const sparkleOnSpy = jest.spyOn(window, 'miqSparkleOn'); const sparkleOffSpy = jest.spyOn(window, 'miqSparkleOff'); const flashSpy = jest.spyOn(window, 'add_flash'); const flashLaterSpy = jest.spyOn(window, 'miqFlashLater'); beforeEach(() => { initialProps = { recordId: null, divisible: false, ancestry: null, redirectUrl: '/foo/bar', }; }); afterEach(() => { fetchMock.reset(); sparkleOnSpy.mockReset(); sparkleOffSpy.mockReset(); flashSpy.mockReset(); flashLaterSpy.mockReset(); }); it('should mount form without initialValues', async(done) => { fetchMock.getOnce(`/api/tenants/${initialProps.recordId}?expand=resources&attributes=name,description,use_config_for_attributes,ancestry,divisible`, { name: 'foo', }); let wrapper; await act(async() => { wrapper = mount(<OpsTenantForm {...initialProps} />); }); wrapper.update(); expect(wrapper.find(MiqFormRenderer).props().initialValues).toEqual({}); expect(fetchMock.calls().length).toEqual(0); expect(sparkleOnSpy).not.toHaveBeenCalled(); expect(sparkleOffSpy).not.toHaveBeenCalled(); done(); }); it('should mount and set initialValues', async(done) => { fetchMock.getOnce('/api/tenants/123?expand=resources&attributes=name,description,use_config_for_attributes,ancestry,divisible', { name: 'foo', }); let wrapper; await act(async() => { wrapper = mount(<OpsTenantForm {...initialProps} recordId={123} />); }); wrapper.update(); expect(wrapper.find(MiqFormRenderer).props().initialValues).toEqual({ name: 'foo', }); expect(fetchMock.calls()).toHaveLength(1); expect(sparkleOnSpy).toHaveBeenCalled(); expect(sparkleOffSpy).toHaveBeenCalled(); done(); }); it('should call miqRedirectBack when canceling form', async(done) => { fetchMock.getOnce('/api/tenants?filter[]=name=&expand=resources', { resources: [], }); let wrapper; await act(async() => { wrapper = mount(<OpsTenantForm {...initialProps} />); }); wrapper.find('button.bx--btn--secondary').first().simulate('click'); expect(miqRedirectBack).toHaveBeenCalledWith('Creation of new Project was canceled by the user.', 'warning', '/foo/bar'); done(); }); it('should correctly add new entity.', async(done) => { fetchMock.getOnce('/api/tenants?filter[]=name=foo&expand=resources', { resources: [], }); fetchMock.postOnce('/api/tenants', {}); const wrapper = mount(<OpsTenantForm {...initialProps} />); wrapper.find('input').at(0).simulate('change', { target: { value: 'foo' } }); wrapper.find('input').at(1).simulate('change', { target: { value: 'bar' } }); wrapper.update(); setTimeout(async() => { await act(async() => { wrapper.find('form').simulate('submit'); }); expect(JSON.parse(fetchMock.calls()[1][1].body)).toEqual({ name: 'foo', description: 'bar', divisible: false, parent: { id: null }, }); expect(miqRedirectBack).toHaveBeenCalledWith('Project "foo" has been successfully added.', 'success', '/foo/bar'); done(); }, 500); }); it('should correctly edit existing entity.', async(done) => { fetchMock.getOnce('/api/tenants/123?expand=resources&attributes=name,description,use_config_for_attributes,ancestry,divisible', { name: 'foo', description: 'bar', ancestry: null, use_config_for_attributes: true, divisible: false, }); fetchMock.getOnce('/api/tenants?filter[]=name=foo&expand=resources', { resources: [], }); fetchMock.putOnce('/api/tenants/123', {}); let wrapper; await act(async() => { wrapper = mount(<OpsTenantForm {...initialProps} recordId={123} />); }); wrapper.update(); await act(async() => { wrapper.find('input').at(1).simulate('change', { target: { value: 'desc' } }); }); wrapper.update(); setTimeout(async() => { await act(async() => { wrapper.find('form').simulate('submit'); }); expect(JSON.parse(fetchMock.calls()[2][1].body)).toEqual({ name: 'foo', description: 'desc', divisible: false, use_config_for_attributes: true, }); expect(miqRedirectBack).toHaveBeenCalledWith('Project "foo" has been successfully saved.', 'success', '/foo/bar'); done(); }, 500); }); });
docs/app/Examples/elements/Segment/Groups/SegmentExamplePiledSegments.js
vageeshb/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExamplePiledSegments = () => ( <Segment.Group piled> <Segment>Top</Segment> <Segment>Middle</Segment> <Segment>Bottom</Segment> </Segment.Group> ) export default SegmentExamplePiledSegments
src/components/Home/Banner.js
tilgram/tilgram-frontend
import React from 'react'; const Banner = ({ appName, token }) => { if (token) { return null; } return ( <div className="banner"> <div className="container"> <h1 className="logo-font"> {appName.toLowerCase()} </h1> <p>A place to share your knowledge.</p> </div> </div> ); }; export default Banner;
src/svg-icons/image/vignette.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageVignette = (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-2zm-9 15c-4.42 0-8-2.69-8-6s3.58-6 8-6 8 2.69 8 6-3.58 6-8 6z"/> </SvgIcon> ); ImageVignette = pure(ImageVignette); ImageVignette.displayName = 'ImageVignette'; ImageVignette.muiName = 'SvgIcon'; export default ImageVignette;
src/svg-icons/device/bluetooth-disabled.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothDisabled = (props) => ( <SvgIcon {...props}> <path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/> </SvgIcon> ); DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled); DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled'; DeviceBluetoothDisabled.muiName = 'SvgIcon'; export default DeviceBluetoothDisabled;
docs/src/pages/premium-themes/onepirate/modules/withRoot.js
lgollut/material-ui
import React from 'react'; import { ThemeProvider } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import theme from './theme'; export default function withRoot(Component) { function WithRoot(props) { return ( <ThemeProvider theme={theme}> {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */} <CssBaseline /> <Component {...props} /> </ThemeProvider> ); } return WithRoot; }
src/components/Footer/index.js
sioked/ecomchicago
import React from 'react'; import { Footer as BFooter, Container, Columns, Column, Title, Content, } from 'bloomer'; import content from '../../constants/content'; function Footer() { return ( <BFooter> <Container> <Columns> <Column isSize="1/2"> <Title isSize="6">{content.footerTitle}</Title> <Columns> <Column isSize="1/2"> <ul className="is-size-6"> <li> <a href="/#about">About</a> </li> <li> <a href="/#speakers">Speakers</a> </li> <li> <a href="/#sponsors">Sponsors</a> </li> <li> <a href="/travel">Travel</a> </li> <li> <a href="/contact">Contact</a> </li> </ul> </Column> <Column isSize="1/2"> <ul className="is-size-6"> <li> <a href="http://2016.ecomchicago.com">ecomChicago 2016</a> </li> <li> <a href="http://2017.ecomchicago.com">ecomChicago 2017</a> </li> <li> <a href="http://2018.ecomchicago.com">ecomChicago 2018</a> </li> <li> <a href="http://2019.ecomchicago.com">ecomChicago 2019</a> </li> </ul> </Column> </Columns> </Column> <Column isSize="1/2" className="has-text-right-tablet"> <Title isSize="6">Attributions</Title> <Content isSize="small"> Podium icon by arejoenah from the Noun Project </Content> </Column> </Columns> </Container> </BFooter> ); } Footer.defaultProps = {}; Footer.propTypes = {}; export default Footer;
tests/components/InterstitialMessage/InterstitialMessage.spec.js
nicklee1990/CompanyIdeas
import React from 'react' import { Navigation } from 'components/Navigation/Navigation' import { IndexLink, Link } from 'react-router' import { shallow } from 'enzyme' import style from 'components/Navigation/Navigation.scss' describe('(Component) InterstitialMessage', () => { let _wrapper beforeEach(() => { _wrapper = shallow(<Navigation />) }) describe('Navigation links...', () => { it('Should render a Link to Tests route', () => { expect(_wrapper.contains( <Link activeClassName={style['route-active']} to="/projects">Tests</Link> )).to.be.true }) it('Should render a Link to Settings route', () => { expect(_wrapper.contains( <Link activeClassName={style['route-active']} to="/settings">Settings</Link> )).to.be.true }) }) })
src/svg-icons/maps/local-bar.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalBar = (props) => ( <SvgIcon {...props}> <path d="M21 5V3H3v2l8 9v5H6v2h12v-2h-5v-5l8-9zM7.43 7L5.66 5h12.69l-1.78 2H7.43z"/> </SvgIcon> ); MapsLocalBar = pure(MapsLocalBar); MapsLocalBar.displayName = 'MapsLocalBar'; MapsLocalBar.muiName = 'SvgIcon'; export default MapsLocalBar;
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
zipongo/react-router
/*globals COURSES:true */ import React from 'react' import { Link } from 'react-router' class AnnouncementsSidebar extends React.Component { render() { let { announcements } = COURSES[this.props.params.courseId] return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ) } } module.exports = AnnouncementsSidebar