path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/index.js
natac13/portfolio-2016
// Immutable dev tools makes for easier viewing of Maps and Lists in the // Chrome Developer tools. import Immutable from 'immutable'; import installDevTools from 'immutable-devtools'; installDevTools(Immutable); import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import { Map } from 'immutable'; import { syncHistoryWithStore } from 'react-router-redux'; import configureRoutes from './routes/configureRoutes.js'; /** Global styles */ import './stylesheets/setup.scss'; import './stylesheets/hamburgers.css'; import './stylesheets/normalize.css'; import configureStore from './store/configureStore'; // seed store with an Immutable.Iterable as per redux-immutable const store = configureStore(Map()); /** Custom select function since the state is using redux-immutable #2 requirement */ const syncOptions = { selectLocationState: (state) => state.get('routing').toJS(), }; const history = syncHistoryWithStore(browserHistory, store, syncOptions); const rootElement = document.getElementById('root'); render(( <Provider store={store}> {configureRoutes(history)} </Provider> ), rootElement);
app/scripts/components/Explore/samples/datasetItem.js
resource-watch/prep-app
import React from 'react'; import Switch from '../../Button/Switch'; export const DATASET_ITEM_SAMPLE = { metadata: { title: 'Title', subtitle: 'Subtitle', description: 'Description', tags: ['Hazard', 'Temperature'] }, leftElement: <Switch onChange={() => {}} checked />, toolsElements: [ (<button key="info-open" onClick={() => {}} className="info"> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><title>info</title><path d="M18.107 14.899v-1.101h-6.603v2.201h2.201v6.603h-2.201v2.201h8.804v-2.201h-2.201v-7.703zm-2.201 16.508C7.397 31.407.499 24.509.499 16S7.397.593 15.906.593 31.313 7.491 31.313 16s-6.898 15.407-15.407 15.407zM13.705 7.196v4.402h4.402V7.196h-4.402z" /></svg> </button>) ], layerActive: true, infoActive: false };
client/components/FlassCommon/Video/VideoVolumeBar/VideoVolumeBar/VideoVolumeBarComponent.js
Nexters/flass
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import { VideoVolumeBar } from './VideoVolumeBarStyled'; import './VideoVolumeBarComponentStyles.scss'; const { func, bool, number } = PropTypes; const propTypes = { onVolumebarClick: func.isRequired, isActive: bool.isRequired, index: number.isRequired }; const defaultProps = { }; class VideoVolumeBarComponent extends Component { render() { const { isActive } = this.props; return ( <VideoVolumeBar isActive={ isActive } onClick={ this.onVolumebarClick }> { ' ' } </VideoVolumeBar> ); } @autobind onVolumebarClick() { const { index } = this.props; this.props.onVolumebarClick(index); } } VideoVolumeBarComponent.propTypes = propTypes; VideoVolumeBarComponent.defaultProps = defaultProps; export default VideoVolumeBarComponent;
client/src/index.js
iwazaru/all-stereotypes-are-wrong
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
geonode/monitoring/frontend/src/components/cels/layer-select/index.js
mcldev/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import actions from './actions'; import styles from './styles'; const mapStateToProps = (state) => ({ interval: state.interval.interval, layers: state.layerList.response, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class GeonodeData extends React.Component { static defaultProps = { fetch: true, } static propTypes = { fetch: PropTypes.bool, get: PropTypes.func.isRequired, interval: PropTypes.number, layers: PropTypes.array, reset: PropTypes.func.isRequired, onChange: PropTypes.func, response: PropTypes.object, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.state = {}; this.handleChange = (target, id, name) => { if (this.props.onChange && this.props.layers[id]) { this.setState({ selected: name }); this.props.onChange(this.props.layers[id].id); } }; } componentWillMount() { if (this.props.fetch) { this.props.get(); } } componentWillReceiveProps(nextProps) { if (nextProps && nextProps.layers && nextProps.layers.length > 0) { const layer = nextProps.layers[0]; const selected = layer.name; this.setState({ selected }); if (this.props.onChange) { this.props.onChange(layer.id); } } } render() { const layers = this.props.layers ? this.props.layers.map((layer) => ( <MenuItem key={layer.id} value={layer.name} primaryText={layer.name} /> )) : null; return ( <DropDownMenu style={styles.root} value={this.state.selected} onChange={this.handleChange} > {layers} </DropDownMenu> ); } } export default GeonodeData;
src/components/OverlayTitle/OverlayTitle.js
Zoomdata/nhtsa-dashboard-2.2
import styles from './OverlayTitle.css'; import React, { Component } from 'react'; import OverlayDescription from '../OverlayDescription/OverlayDescription'; class OverlayTitle extends Component { render() { const { makeWrapperDimensions, aboutVisibility, hideOverlay } = this.props; const overlayTitleStyle = { top: makeWrapperDimensions.offsetTop, left: makeWrapperDimensions.offsetLeft + makeWrapperDimensions.width + 75 }; if (hideOverlay) { if (aboutVisibility === 'OPEN_ABOUT') { this.overlayTitleStyle = { top: makeWrapperDimensions.offsetTop, left: makeWrapperDimensions.offsetLeft + makeWrapperDimensions.width + 75, display: 'none' }; } } else { this.overlayTitleStyle = { top: makeWrapperDimensions.offsetTop, left: makeWrapperDimensions.offsetLeft + makeWrapperDimensions.width + 75, display: 'block' } } return ( <div className={styles.root} style={ this.overlayTitleStyle ? this.overlayTitleStyle : overlayTitleStyle } > VEHICLE <br /> COMPLAINTS <OverlayDescription /> </div> ) } }; export default OverlayTitle;
resources/src/js/components/Player/FloatingPlayer.js
aberon10/thermomusic.com
'use strict'; import React from 'react'; import displayPlayer from './animation'; export default class FloatingPlayer extends React.Component { render() { return( <div className="floating-player" id="floating-player"> <div className="floating-player__left"> <button className="control-button toggle-button-player" id="open-player" onClick={displayPlayer}> <i className="icon-arrow-up"></i> </button> </div> <div className="floating-player__center"> <div className="track-info"> <div className="track-info__name"> <h4>Album</h4> </div> <div className="track-info__artists"> <h5>Artista</h5> </div> </div> </div> <div className="floating-player__right"> <button className="control-button floating-button-play" id="secondary-button-play"> <i className="icon-play-2"></i> </button> </div> <div className="playback-bar"> <div className="progress-bar" id="secondary-bar"> <div className="progress-bar__loading"></div> <div className="progress-bar__player"></div> </div> </div> </div> ); } }
src/svg-icons/maps/local-airport.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalAirport = (props) => ( <SvgIcon {...props}> <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/> </SvgIcon> ); MapsLocalAirport = pure(MapsLocalAirport); MapsLocalAirport.displayName = 'MapsLocalAirport'; MapsLocalAirport.muiName = 'SvgIcon'; export default MapsLocalAirport;
src/docs/apiExamples/LabelList.js
recharts/recharts.org
import React from 'react'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Label, LabelList } from 'recharts'; const data = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, ]; const chartExample = () => ( <BarChart width={730} height={250} data={data} margin={{ top: 15, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name"> <Label value="Pages of my website" offset={0} position="insideBottom" /> </XAxis> <YAxis label={{ value: 'pv of page', angle: -90, position: 'insideLeft', textAnchor: 'middle', }} /> <Bar dataKey="pv" fill="#8884d8"> <LabelList dataKey="name" position="insideTop" angle={45} /> </Bar> <Bar dataKey="uv" fill="#82ca9d"> <LabelList dataKey="uv" position="top" /> </Bar> </BarChart> ); export default [ { demo: chartExample, code: ` <BarChart width={730} height={250} data={data} margin={{ top: 15, right: 30, left: 20, bottom: 5 }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name"> <Label value="Pages of my website" offset={0} position="insideBottom" /> </XAxis> <YAxis label={{ value: 'pv of page', angle: -90, position: 'insideLeft', textAnchor: 'middle' }} /> <Bar dataKey="pv" fill="#8884d8"> <LabelList dataKey="name" position="insideTop" angle="45" /> </Bar> <Bar dataKey="uv" fill="#82ca9d"> <LabelList dataKey="uv" position="top" /> </Bar> </BarChart> `, dataCode: `const data = ${JSON.stringify(data, null, 2)}`, }, ];
src/components/Feedback/Feedback.js
grantgeorge/react-app
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.less'; 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;
src/views/NotFoundView/NotFoundView.js
itjope/tipskampen
import React from 'react' import { Link } from 'react-router' export class NotFoundView extends React.Component { render () { return ( <div className='container text-center'> <h1>This is a demo 404 page!</h1> <hr /> <Link to='/'>Back To Home View</Link> </div> ) } } export default NotFoundView
app/Recipezy.js
hippothesis/Recipezy
/* * Copyright 2017-present, Hippothesis, 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. */ 'use strict'; import React, { Component } from 'react'; import { Provider } from 'react-redux'; import Store from './store/Store'; import AppNavigatorView from './views/AppNavigatorView'; export default class Recipezy extends Component { render() { return ( <Provider store={Store}> <AppNavigatorView /> </Provider> ); } }
src/containers/App/App.js
Nuriddinkhuja/photoshare
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Header from '../Header/Header'; export default class App extends Component { static propTypes = { children: PropTypes.object.isRequired }; render() { const { children } = this.props; return ( <div> <Header /> <div className="ui container"> {children} </div> </div> ); } }
Realization/frontend/czechidm-core/src/content/role/RoleDetail.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import Helmet from 'react-helmet'; import _ from 'lodash'; import { connect } from 'react-redux'; import uuid from 'uuid'; // import * as Basic from '../../components/basic'; import * as Advanced from '../../components/advanced'; import * as Utils from '../../utils'; import RoleTypeEnum from '../../enums/RoleTypeEnum'; import RolePriorityEnum from '../../enums/RolePriorityEnum'; import { RoleManager, SecurityManager, RequestManager, ConfigurationManager } from '../../redux'; import RequestTable from '../request/RequestTable'; import SearchParameters from '../../domain/SearchParameters'; let roleManager = null; const uiKeyRoleRequest = 'role-universal-request-table'; const requestManager = new RequestManager(); /** * Role detail * * @author Ondřej Kopr * @author Radek Tomiška */ class RoleDetail extends Basic.AbstractContent { constructor(props) { super(props); this.state = { _showLoading: true, activeKey: 1 }; } getContentKey() { return 'content.roles'; } componentDidMount() { const { entity } = this.props; // Init manager - evaluates if we want to use standard (original) manager or // universal request manager (depends on existing of 'requestId' param) roleManager = this.getRequestManager(this.props.match.params, new RoleManager()); if (Utils.Entity.isNew(entity)) { entity.priorityEnum = RolePriorityEnum.findKeyBySymbol(RolePriorityEnum.NONE); entity.priority = `${RolePriorityEnum.getPriority(RolePriorityEnum.NONE)}`; this._setSelectedEntity(entity); } else { this._setSelectedEntity(this._prepareEntity(entity)); } } // @Deprecated - since V10 ... replaced by dynamic key in Route // UNSAFE_componentWillReceiveProps(nextProps) { // const { entity } = this.props; // if ((nextProps.match.params && this.props.match.params && nextProps.match.params.requestId !== this.props.match.params.requestId) // || (nextProps.entity && nextProps.entity !== entity)) { // // Init manager - evaluates if we want to use standard (original) manager or // // universal request manager (depends on existing of 'requestId' param) // roleManager = this.getRequestManager(nextProps.match.params, new RoleManager()); // } // if (nextProps.entity && nextProps.entity !== entity && nextProps.entity) { // this._setSelectedEntity(this._prepareEntity(nextProps.entity)); // } // } _prepareEntity(entity) { const copyOfEntity = _.merge({}, entity); // we can not modify given entity // we dont need to load entities again - we have them in embedded objects copyOfEntity.priorityEnum = RolePriorityEnum.findKeyBySymbol(RolePriorityEnum.getKeyByPriority(copyOfEntity.priority)); copyOfEntity.priority += ''; // We have to do convert form int to string (cause TextField and validator) return copyOfEntity; } _setSelectedEntity(entity) { this.setState({ _showLoading: false }, () => { entity.codeable = { code: entity.baseCode, name: entity.name }; this.refs.form.setData(entity); this.refs.codeable.focus(); }); } save(afterAction, event) { if (event) { event.preventDefault(); } if (!this.refs.form.isFormValid()) { return; } this.setState({ _showLoading: true }, () => { const entity = this.refs.form.getData(); entity.baseCode = entity.codeable.code; entity.name = entity.codeable.name; this.refs.form.processStarted(); // this.getLogger().debug('[RoleDetail] save entity', entity); if (Utils.Entity.isNew(entity)) { this.context.store.dispatch(roleManager.createEntity(entity, null, (createdEntity, error) => { this._afterSave(createdEntity, error, afterAction); })); } else { this.context.store.dispatch(roleManager.updateEntity(entity, null, (patchedEntity, error) => { this._afterSave(patchedEntity, error, afterAction); })); } }); } _afterSave(entity, error, afterAction = 'CLOSE') { this.setState({ _showLoading: false }, () => { this.refs.form.processEnded(); if (error) { this.addError(error); return; } // this.addMessage({ message: this.i18n('save.success', { name: entity.name }) }); if (afterAction === 'CLOSE') { this.context.history.replace(this.addRequestPrefix('roles', this.props.match.params)); } else if (afterAction === 'NEW') { const uuidId = uuid.v1(); const newEntity = { priority: `${ RolePriorityEnum.getPriority(RolePriorityEnum.NONE) }`, // conversion to string priorityEnum: RolePriorityEnum.findKeyBySymbol(RolePriorityEnum.NONE) }; this.context.store.dispatch(roleManager.receiveEntity(uuidId, newEntity)); this.context.history.replace(`${this.addRequestPrefix('role', this.props.match.params)}/${ uuidId }/new?new=1`); this._setSelectedEntity(newEntity); } else { this.context.history.replace(`${this.addRequestPrefix('role', this.props.match.params) }/${ entity.id }/detail`); // reload code (baseCode|environment) in form is needed ... TODO: data prop on form can be used instead. this._setSelectedEntity(this._prepareEntity(entity)); } }); } _onChangePriorityEnum(item) { if (item) { const priority = RolePriorityEnum.getPriority(item.value); this.refs.priority.setValue(`${ priority }`); } else { this.refs.priority.setValue(null); } } _onChangeSelectTabs(activeKey) { this.setState({ activeKey }); } render() { const { entity, showLoading, _permissions, _requestUi, showEnvironment } = this.props; const { _showLoading, activeKey } = this.state; if (!roleManager || !entity) { return null; } let requestsForceSearch = new SearchParameters(); requestsForceSearch = requestsForceSearch.setFilter('ownerId', entity.id ? entity.id : SearchParameters.BLANK_UUID); requestsForceSearch = requestsForceSearch.setFilter('ownerType', 'eu.bcvsolutions.idm.core.api.dto.IdmRoleDto'); requestsForceSearch = requestsForceSearch.setFilter('states', ['IN_PROGRESS', 'CONCEPT', 'EXCEPTION']); // return ( <Basic.Div style={{ paddingTop: 15 }}> <Helmet title={ Utils.Entity.isNew(entity) ? this.i18n('create.header') : this.i18n('edit.title') } /> <Basic.Tabs activeKey={ activeKey } onSelect={ this._onChangeSelectTabs.bind(this)}> <Basic.Tab eventKey={ 1 } title={ this.i18n('entity.Role._type') } className="bordered"> <form onSubmit={ this.save.bind(this, 'CONTINUE') }> <Basic.ContentHeader text={ Utils.Entity.isNew(entity) ? this.i18n('create.header') : this.i18n('tabs.basic') } style={{ marginBottom: 0, paddingTop: 15, paddingRight: 15, paddingLeft: 15 }}/> <Basic.Panel className="no-border last"> <Basic.PanelBody style={{ paddingTop: 0, paddingBottom: 0 }}> <Basic.AbstractForm ref="form" showLoading={ _showLoading || showLoading } readOnly={ !roleManager.canSave(entity, _permissions) }> <Advanced.CodeableField ref="codeable" codeLabel={ this.i18n('entity.Role.baseCode.label') } codeHelpBlock={ this.i18n('entity.Role.baseCode.help') } nameLabel={ this.i18n('entity.Role.name') }/> <Basic.Row> <Basic.Col lg={ 4 }> <Advanced.CodeListSelect ref="environment" hidden={ !showEnvironment } code="environment" label={ this.i18n('entity.Role.environment.label') } helpBlock={ this.i18n( `entity.Role.environment.${ entity.environment ? 'helpCode' : 'help' }`, { escape: false, code: entity.code } ) } max={ 255 }/> </Basic.Col> <Basic.Col lg={ 8 }> <Basic.EnumSelectBox ref="roleType" label={ this.i18n('entity.Role.roleType') } enum={ RoleTypeEnum } useSymbol={ false }/> </Basic.Col> </Basic.Row> <Basic.EnumSelectBox ref="priorityEnum" label={ this.i18n('entity.Role.priorityEnum') } enum={ RolePriorityEnum } onChange={ this._onChangePriorityEnum.bind(this) } clearable={ false } required/> <Basic.TextField ref="priority" label={ this.i18n('entity.Role.priority') } readOnly required/> <Basic.Checkbox ref="approveRemove" label={ this.i18n('entity.Role.approveRemove') }/> <Basic.Checkbox ref="canBeRequested" label={ this.i18n('entity.Role.canBeRequested') }/> <Basic.TextArea ref="description" label={ this.i18n('entity.Role.description') } max={2000}/> <Basic.Checkbox ref="disabled" label={ this.i18n('entity.Role.disabled') }/> </Basic.AbstractForm> </Basic.PanelBody> <Basic.PanelFooter style={{ paddingLeft: 15, paddingRight: 15 }}> <Basic.Button type="button" level="link" onClick={this.context.history.goBack} showLoading={ _showLoading} > { this.i18n('button.back') } </Basic.Button> <Basic.SplitButton level="success" title={ this.i18n('button.saveAndContinue') } onClick={ this.save.bind(this, 'CONTINUE') } showLoading={ _showLoading } showLoadingIcon showLoadingText={ this.i18n('button.saving') } rendered={ roleManager.canSave(entity, _permissions) } pullRight dropup> <Basic.MenuItem eventKey="1" onClick={ this.save.bind(this, 'CLOSE') }> {this.i18n('button.saveAndClose')} </Basic.MenuItem> <Basic.MenuItem eventKey="2" onClick={ this.save.bind(this, 'NEW') } rendered={ SecurityManager.hasAuthority('ROLE_CREATE') }> { this.i18n('button.saveAndNew') } </Basic.MenuItem> </Basic.SplitButton> </Basic.PanelFooter> </Basic.Panel> {/* onEnter action - is needed because SplitButton is used instead standard submit button */} <input type="submit" className="hidden"/> </form> </Basic.Tab> <Basic.Tab eventKey={ 2 } rendered={ !!(entity.id && SecurityManager.hasAuthority('REQUEST_READ')) } disabled={ roleManager.isRequestModeEnabled() || !entity.id } title={ <span> { this.i18n('content.requests.header') } <Basic.Badge level="warning" style={{ marginLeft: 5 }} text={ _requestUi ? _requestUi.total : null } rendered={!roleManager.isRequestModeEnabled() && _requestUi && _requestUi.total > 0 } title={ this.i18n('content.requests.header') }/> </span> } className="bordered"> <Basic.ContentHeader text={ this.i18n('content.requests.header', { escape: false }) } style={{ marginBottom: 0, paddingTop: 15, paddingRight: 15, paddingLeft: 15 }}/> <RequestTable ref="table" uiKey={ uiKeyRoleRequest } forceSearchParameters={ requestsForceSearch } showFilter={false} showLoading={ _showLoading } manager={ requestManager } columns={[ 'state', 'created', 'modified', 'wf', 'detail' ]}/> </Basic.Tab> </Basic.Tabs> </Basic.Div> ); } } RoleDetail.propTypes = { entity: PropTypes.object, showLoading: PropTypes.bool, _permissions: PropTypes.arrayOf(PropTypes.string) }; RoleDetail.defaultProps = { _permissions: null }; function select(state, component) { const result = { showEnvironment: ConfigurationManager.getPublicValueAsBoolean(state, 'idm.pub.app.show.environment', true) }; // if (!roleManager) { return result; } if (!component.entity) { return result; } return { ...result, _permissions: roleManager.getPermissions(state, null, component.entity.id), _requestUi: Utils.Ui.getUiState(state, uiKeyRoleRequest) }; } export default connect(select)(RoleDetail);
packages/starter-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js
chungchiehlun/create-starter-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, { Component } from 'react'; import PropTypes from 'prop-types'; function load(prefix) { return [ { id: 1, [`${prefix} name`]: '1' }, { id: 2, [`${prefix} name`]: '2' }, { id: 3, [`${prefix} name`]: '3' }, { id: 4, [`${prefix} name`]: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load('user_'); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-computed-properties"> {this.state.users.map(user => ( <div key={user.id}>{user.user_name}</div> ))} </div> ); } }
packages/lore-tutorial/templates/es6/step2/src/components/Layout.js
lore/lore
/** * This component is intended to reflect the high level structure of your application, * and render any components that are common across all views, such as the header or * top-level navigation. All other components should be rendered by route handlers. **/ import React from 'react'; import Header from './Header'; export default class Layout extends React.Component { render() { return ( <div> <Header /> <div className="container"> <div className="row"> <div className="col-md-offset-3 col-md-6"> {/* Feed will go here */} </div> </div> </div> </div> ); } }
src/components/Username/WithCard.js
welovekpop/uwave-web-welovekpop.club
import React from 'react'; import PropTypes from 'prop-types'; import compose from 'recompose/compose'; import withProps from 'recompose/withProps'; import userCardable from '../../utils/userCardable'; import UsernameBase from '.'; const enhance = compose( userCardable(), withProps(props => ({ onUsernameClick(event) { const { openUserCard, user } = props; event.preventDefault(); openUserCard(user); }, })), ); const UsernameWithCard = ({ user, onUsernameClick }) => ( <button type="button" onClick={onUsernameClick}> <UsernameBase user={user} /> </button> ); UsernameWithCard.propTypes = { user: PropTypes.object.isRequired, onUsernameClick: PropTypes.func.isRequired, }; export default enhance(UsernameWithCard);
example/main.js
teosz/react-chartist
import React from 'react'; import ChartistGraph from '../index'; class Pie extends React.Component { render() { var data = { labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], series: [ [1, 2, 4, 8, 6, -2, -1, -4, -6, -2] ] }; var options = { high: 10, low: -10, axisX: { labelInterpolationFnc: function(value, index) { return index % 2 === 0 ? value : null; } } }; var type = 'Bar' return ( <div> <ChartistGraph data={data} options={options} type={type} /> </div> ) } } React.render(<Pie />, document.body)
src/packages/@ncigdc/utils/withControlledAccess/index.js
NCI-GDC/portal-ui
import React from 'react'; import { connect } from 'react-redux'; import { isEqual, omit, } from 'lodash'; import { compose, lifecycle, setDisplayName, withHandlers, withPropsOnChange, withState, } from 'recompose'; import { fetchApi } from '@ncigdc/utils/ajax'; import withRouter from '@ncigdc/utils/withRouter'; import ControlledAccessModal from '@ncigdc/components/Modals/ControlledAccess'; import { setModal } from '@ncigdc/dux/modal'; import { DEV_USER, DEV_USER_CA, DISPLAY_DAVE_CA, IS_DEV, } from '@ncigdc/utils/constants'; import { reshapeSummary, reshapeUserAccess, } from './helpers'; export default compose( setDisplayName('withControlledAccess'), withRouter, connect(state => ({ token: state.auth.token, user: state.auth.user, userControlledAccess: state.auth.userControlledAccess, })), withState('studiesSummary', 'setStudiesSummary', { controlled: [], in_process: [], open: [], }), withHandlers({ clearUserAccess: ({ dispatch, userControlledAccess = { studies: {} }, }) => () => { Object.keys(userControlledAccess.studies).length > 0 && dispatch({ type: 'gdc/USER_CONTROLLED_ACCESS_CLEAR' }); }, fetchStudiesList: ({ setStudiesSummary }) => () => ( fetchApi( '/studies/summary/all', { headers: { 'Content-Type': 'application/json', }, }, ) .then(({ data } = {}) => { data && setStudiesSummary(reshapeSummary(data)); }) .catch(error => console.error(error)) ), storeUserAccess: ({ dispatch, }) => controlled => { dispatch({ payload: reshapeUserAccess(controlled), type: 'gdc/USER_CONTROLLED_ACCESS_SUCCESS', }); }, }), lifecycle({ componentDidMount() { const { fetchStudiesList, } = this.props; DISPLAY_DAVE_CA && fetchStudiesList(); }, }), withPropsOnChange( ( { user, }, { user: nextUser, }, ) => !( isEqual(user, nextUser) ), ({ clearUserAccess, storeUserAccess, user, userControlledAccess, }) => (user && DISPLAY_DAVE_CA ? userControlledAccess.fetched || ( IS_DEV || DEV_USER ? storeUserAccess(DEV_USER_CA) : fetchApi('/studies/user') .then(({ data }) => { storeUserAccess(data.controlled); }) .catch(error => { console.error('while fetching user controlled access', error); clearUserAccess(); }) ) : clearUserAccess() ), ), withPropsOnChange( ( { query: { controlled, }, studiesSummary, user, }, { query: { controlled: nextControlled, }, studiesSummary: nextStudiesSummary, user: nextUser, }, ) => !( controlled === nextControlled && isEqual(studiesSummary, nextStudiesSummary) && isEqual(user, nextUser) ), ({ dispatch, location: { pathname, }, push, query, query: { controlled = '', }, studiesSummary, user, userControlledAccess, }) => { // gets the whole array of 'controlled' from the URL const controlledQuery = Array.isArray(controlled) ? controlled.map(study => study.toLowerCase().split(',')).flat() : controlled.toLowerCase().split(','); // distills the list const controlledStudies = user && controlled.length > 0 ? controlledQuery.filter((study, index, self) => ( Object.keys(userControlledAccess.studies || {}).includes(study) && // is it allowed? index === self.indexOf(study) // is it unique? )).sort() : []; // validates and corrects the displayed URL if necessary (controlledStudies.length > 1 ||// Single study. Remove it when ready. !( controlledStudies.every(study => study.toUpperCase() === study) && // any study in lowercase controlledStudies.length === controlledQuery.length // any invalid study )) && push({ pathname, ...(controlledStudies.length ? { query: { ...query, controlled: controlledStudies[0].toUpperCase(), // Single study. Remove it when ready. // controlled: controlledStudies.map(study => study.toUpperCase()), // clean URL // ^^^ ready for whenever they enable querying multiple controlled studies }, queryOptions: { arrayFormat: 'comma' }, } : { query: omit(query, ['controlled']), } ), }); return { controlledAccessProps: DISPLAY_DAVE_CA ? { controlledStudies, showControlledAccessModal: () => { dispatch(setModal( <ControlledAccessModal activeControlledPrograms={controlledStudies} closeModal={() => dispatch(setModal(null))} studiesSummary={studiesSummary} />, )); }, } : {}, }; }, ), );
src/routes/Counter/components/Counter.js
mje0002/originReact
import React from 'react' export const Counter = (props) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {props.counter}</h2> <button className='btn btn-default' onClick={props.increment}> Increment </button> {' '} <button className='btn btn-default' onClick={props.doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter : React.PropTypes.number.isRequired, doubleAsync : React.PropTypes.func.isRequired, increment : React.PropTypes.func.isRequired } export default Counter
tests/react/src/components/App.js
fruuf/pack
import React from 'react'; import Message from '/components/Message'; import './app.scss'; export default () => ( <div className="app"> <Message /> </div> );
src/components/searchbar/searchbar.js
woshisbb43/coinMessageWechat
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import classNames from '../../utils/classnames'; import Icon from '../icon'; /** * weui search component * */ class SearchBar extends React.Component { static propTypes = { /** * default value for the searchbar if any * */ defaultValue: PropTypes.string, /** * default place holder text * */ placeholder: PropTypes.string, /** * name of the input component * */ searchName: PropTypes.string, /** * trigger when text change on input pass `text` property * */ onChange: PropTypes.func, /** * trigger when user click clear icon * */ onClear: PropTypes.func, /** * trigger when user click cancel button * */ onCancel: PropTypes.func, /** * trigger when user submit (enter action) * */ onSubmit: PropTypes.func, /** * language object consists of `cancel` property * */ lang: PropTypes.object }; static defaultProps = { placeholder: '搜索', searchName: 'q', onChange: undefined, onClear: undefined, onCancel: undefined, onSubmit: undefined, lang: { cancel: '取消' }, autocomplete: 'off' }; constructor(props){ super(props); this.state = { focus: this.props.defaultValue ? true : false, clearing: false, text: this.props.defaultValue ? this.props.defaultValue : '' }; if (this.props.defaultValue !== ''){ if (this.props.onChange) this.props.onChange(this.state.text); } } changeHandle(e) { let text = e.target.value; if (this.props.onChange) this.props.onChange(text, e); this.setState({text}); } cancelHandle(e) { this.setState({ focus: false, text: '' }); if (this.props.onCancel) this.props.onCancel(e); if (this.props.onChange) this.props.onChange('', e); } clearHandle(e) { e.preventDefault(); e.stopPropagation(); this.setState({text: '', clearing: true}); if (this.props.onClear) this.props.onClear(e); // In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all. // When render returns null or false, findDOMNode returns null. // 这里是截取官网的说明,在ref回调函数内确实会返回null,尤其是配合redux使用的时候,这个时候需要对其进行null判断 this.refs.searchInput.focus(); // ReactDOM.findDOMNode(this.refs.searchInput).focus() if (this.props.onChange) this.props.onChange('', e); } blurHandle(e) { if (this.state.text === ''){ this.setState({ focus: false}); } } submitHandle(e) { if (this.props.onSubmit) { e.preventDefault(); e.stopPropagation(); this.props.onSubmit(this.state.text, e); } } render() { const {children, defaultValue, autocomplete, placeholder, className, searchName} = this.props; const clz = classNames({ 'weui-search-bar': true, 'weui-search-bar_focusing': this.state.focus }, className); return ( <div className={clz}> <form className='weui-search-bar__form' onSubmit={this.submitHandle.bind(this)}> <div className='weui-search-bar__box'> <Icon value='search'/> <input ref='searchInput' type='search' name={searchName} className='weui-search-bar__input' placeholder={placeholder} onFocus={e=>this.setState({focus: true})} onBlur={this.blurHandle.bind(this)} onChange={this.changeHandle.bind(this)} value={this.state.text} autoComplete={autocomplete} /> {/*React will not trigger onMouseDown when not onClick presented*/} <a className='weui-icon-clear' onClick={this.clearHandle.bind(this)} /> </div> <label className='weui-search-bar__label' onClick={()=>{ let searchInput = this.refs.searchInput; if (searchInput) { searchInput.focus(); } }} style={{display: this.state.text ? 'none' : null}} > <Icon value='search'/> <span>{placeholder}</span> </label> </form> <a className='weui-search-bar__cancel-btn' onClick={this.cancelHandle.bind(this)}>{this.props.lang.cancel}</a> </div> ); } } export default SearchBar;
src/parser/druid/guardian/modules/spells/IronFur.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SCHOOLS from 'game/MAGIC_SCHOOLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; const debug = false; class IronFur extends Analyzer { _hitsPerStack = []; registerHit(stackCount) { if (!this._hitsPerStack[stackCount]) { this._hitsPerStack[stackCount] = 0; } this._hitsPerStack[stackCount] += 1; } on_toPlayer_damage(event) { // Physical if (event.ability.type === SCHOOLS.ids.PHYSICAL) { const ironfur = this.selectedCombatant.getBuff(SPELLS.IRONFUR.id); this.registerHit(ironfur ? ironfur.stacks : 0); } } get hitsMitigated() { return this._hitsPerStack.slice(1).reduce((sum, x) => sum + x, 0); } get hitsUnmitigated() { return this._hitsPerStack[0] || 0; } get ironfurStacksApplied() { return this._hitsPerStack.reduce((sum, x, i) => sum + (x * i), 0); } get totalHitsTaken() { return this._hitsPerStack.reduce((sum, x) => sum + x, 0); } get overallIronfurUptime() { // Avoid NaN display errors if (this.totalHitsTaken === 0) { return 0; } return this.ironfurStacksApplied / this.totalHitsTaken; } get percentOfHitsMitigated() { if (this.totalHitsTaken === 0) { return 0; } return this.hitsMitigated / this.totalHitsTaken; } computeIronfurUptimeArray() { return this._hitsPerStack.map(hits => hits / this.totalHitsTaken); } on_fightend() { if (debug) { console.log(`Hits with ironfur ${this.hitsMitigated}`); console.log(`Hits without ironfur ${this.hitsUnmitigated}`); console.log('Ironfur uptimes:', this.computeIronfurUptimeArray()); } } suggestions(when) { when(this.percentOfHitsMitigated).isLessThan(0.90) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>You only had the <SpellLink id={SPELLS.IRONFUR.id} /> buff for {formatPercentage(actual)}% of physical damage taken. You should have the Ironfur buff up to mitigate as much physical damage as possible.</span>) .icon(SPELLS.IRONFUR.icon) .actual(`${formatPercentage(actual)}% was mitigated by Ironfur`) .recommended(`${Math.round(formatPercentage(recommended))}% or more is recommended`) .regular(recommended - 0.10).major(recommended - 0.2); }); } statistic() { const totalIronFurTime = this.selectedCombatant.getBuffUptime(SPELLS.IRONFUR.id); const uptimes = this.computeIronfurUptimeArray().reduce((str, uptime, stackCount) => ( <>{str}<li>{stackCount} stack{stackCount !== 1 ? 's' : ''}: {formatPercentage(uptime)}%</li></> ), null); return ( <StatisticBox position={STATISTIC_ORDER.CORE(10)} icon={<SpellIcon id={SPELLS.IRONFUR.id} />} value={`${formatPercentage(this.percentOfHitsMitigated)}% / ${this.overallIronfurUptime.toFixed(2)}`} label="Hits mitigated with Ironfur / Average Stacks" tooltip={( <> Ironfur usage breakdown: <ul> <li>You were hit <strong>{this.hitsMitigated}</strong> times with your Ironfur buff.</li> <li>You were hit <strong>{this.hitsUnmitigated}</strong> times <strong><em>without</em></strong> your Ironfur buff.</li> </ul> <strong>Uptimes per stack: </strong> <ul> {uptimes} </ul> <strong>{formatPercentage(this.percentOfHitsMitigated)}%</strong> of physical attacks were mitigated with Ironfur, and your overall uptime was <strong>{formatPercentage(totalIronFurTime / this.owner.fightDuration)}%</strong>. </> )} /> ); } } export default IronFur;
src/map/js/components/LayerPanel/WaterStressLegend.js
wri/gfw-water
import {layerPanelText} from 'js/config'; import Request from 'utils/request'; import React from 'react'; export default class WaterStressLegend extends React.Component { constructor(props) { super(props); //- Set legend Info to an empty array until data is returned this.state = { legendInfoLevels: [], legendInfoNoData: [] }; } componentDidMount() { Request.getLegendInfos(this.props.url, this.props.layerIds).then(legendInfos => { this.setState({ legendInfoLevels: legendInfos.slice(0, legendInfos.length - 2), legendInfoNoData: legendInfos.slice(legendInfos.length - 2) }); }); } shouldComponentUpdate(nextProps, nextState) { return nextState.legendInfoLevels.length !== this.state.legendInfoLevels.length; } render() { return ( <div className='legend-container'> {this.state.legendInfoLevels.length === 0 ? <div className='legend-unavailable'>No Legend</div> : <div className='water-stress-legend'> <div className='legend-row'> <div className='legend-label'>{layerPanelText.waterStressLegend.min}</div> {this.state.legendInfoLevels.map(this.imgMapper, this)} <div className='legend-label'>{layerPanelText.waterStressLegend.max}</div> </div> <div className='legend-row no-data-labels'> <div className='legend-label'>{layerPanelText.waterStressLegend.arid}</div> <div className='legend-label'>{layerPanelText.waterStressLegend.nodata}</div> {this.state.legendInfoNoData.map(this.imgMapper, this)} </div> </div> } </div> ); } imgMapper (legendInfo, index) { return <img key={index} title={legendInfo.label} src={`data:image/png;base64,${legendInfo.imageData}`} />; } } WaterStressLegend.propTypes = { url: React.PropTypes.string.isRequired, layerIds: React.PropTypes.array.isRequired };
app/js/components/ColorDisplay.js
raulalgo/scales-react
'use strict'; import React from 'react'; import Colorable from 'colorable'; var divStyle = { backgroundColor: 'rgb(255,255,0)', minWidth: '100%' } var textClass = "darkText" class ColorDisplay extends React.Component{ constructor(props) { super(props); } defaultState () { } render() { var numero = 100; var htmlColor = this.rgb2hex(this.props.bgRed, this.props.bgGreen, this.props.bgBlue) divStyle.backgroundColor = "rgb(" + this.props.bgRed + "," + this.props.bgGreen + "," + this.props.bgBlue + ")" ; var colors = { background: htmlColor, black: '#000000', white: '#FFFFFF' } var options = { compact: true, threshold: 0 }; var result = Colorable(colors, options); if (result[0].combinations[0].contrast<4) textClass = "lightText" else textClass = "darkText" return ( <div id="colorDisplay" className={this.props.cdClass} style={divStyle} ><span className={textClass}>{htmlColor}</span></div> ); } componentToHex (c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } rgb2hex (r,g,b) { return "#" + this.componentToHex(+r) + this.componentToHex(+g) + this.componentToHex(+b) } } export default ColorDisplay;
src/svg-icons/file/cloud-download.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudDownload = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z"/> </SvgIcon> ); FileCloudDownload = pure(FileCloudDownload); FileCloudDownload.displayName = 'FileCloudDownload'; FileCloudDownload.muiName = 'SvgIcon'; export default FileCloudDownload;
src/parser/rogue/subtlety/modules/core/NightbladeUptime.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Enemies from 'parser/shared/modules/Enemies'; import StatisticBox from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatNumber } from 'common/format'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import DamageTracker from 'parser/shared/modules/AbilityTracker'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; const ABILITIES_AFFECTED_BY_NIGHTBLADE = [ SPELLS.SECRET_TECHNIQUE_TALENT, SPELLS.GLOOMBLADE_TALENT, SPELLS.EVISCERATE, SPELLS.BACKSTAB, SPELLS.SHURIKEN_TOSS, SPELLS.SHADOWSTRIKE, SPELLS.SHURIKEN_STORM, ]; class NightbladeUptime extends Analyzer { static dependencies = { enemies: Enemies, damageTracker: DamageTracker, }; constructor(...args) { super(...args); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(ABILITIES_AFFECTED_BY_NIGHTBLADE), this.handleDamage); } buffedDamage = 0; totalDamage = 0; damageBonus = 0; handleDamage(event) { const target = this.enemies.getEntity(event); if (!target) { return; } if(target.hasBuff(SPELLS.NIGHTBLADE.id)){ this.buffedDamage += calculateEffectiveDamage(event,1); this.damageBonus += calculateEffectiveDamage(event,0.15); } this.totalDamage += calculateEffectiveDamage(event,1); } get percentUptime() { return this.enemies.getBuffUptime(SPELLS.NIGHTBLADE.id) / this.owner.fightDuration; } get buffedPercent() { return 1 - (this.totalDamage - this.buffedDamage) / this.totalDamage; } get uptimeThresholds() { return { actual: this.percentUptime, isLessThan: { minor: 0.98, average: 0.95, major: 0.9, }, style: 'percentage', }; } get effectThresholds() { return { actual: this.buffedPercent, isLessThan: { minor: 0.95, average: 0.9, major: 0.8, }, style: 'percentage', }; } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(120)} icon={<SpellIcon id={SPELLS.NIGHTBLADE.id} />} value={`${formatPercentage(this.buffedPercent)}%`} label={`Damage Buffed by Nightblade`} tooltip={<>You buffed <b> {formatPercentage(this.buffedPercent)}% </b> of your damage by Nightblade. <br />The total increase was <b>{formatNumber(this.damageBonus/this.owner.fightDuration * 1000)} DPS </b></>} /> ); } } export default NightbladeUptime;
src/parser/deathknight/blood/modules/talents/Tombstone.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import SpellLink from 'common/SpellLink'; import { formatNumber, formatPercentage } from 'common/format'; import DamageTracker from 'parser/shared/modules/AbilityTracker'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import { TooltipElement } from 'common/Tooltip'; const RPPERCHARGE = 6; const MAXCHARGES = 5; class Tombstone extends Analyzer { static dependencies = { damageTracker: DamageTracker, }; tombstone = []; casts = 0; rpGained = 0; rpWasted = 0; absorbSize = 0; totalAbsorbed = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.TOMBSTONE_TALENT.id); } get wastedCasts() { return this.tombstone.filter(e => e.charges < MAXCHARGES).length; } on_toPlayer_applybuff(event) { if (event.ability.guid !== SPELLS.TOMBSTONE_TALENT.id) { return; } this.casts += 1; this.absorbSize = event.absorb; } on_toPlayer_energize(event) { if (event.ability.guid !== SPELLS.TOMBSTONE_TALENT.id) { return; } this.rpGained = event.resourceChange; this.rpWasted = event.waste; } on_toPlayer_absorbed(event) { if (event.ability.guid !== SPELLS.TOMBSTONE_TALENT.id) { return; } this.totalAbsorbed += event.amount; } on_toPlayer_removebuff(event) { if (event.ability.guid !== SPELLS.TOMBSTONE_TALENT.id) { return; } this.tombstone.push({ rpGained: this.rpGained, rpWasted: this.rpWasted, absorbSize: this.absorbSize, totalAbsorbed: this.totalAbsorbed, absorbedWasted: (this.absorbSize - this.totalAbsorbed), charges: (this.rpGained / RPPERCHARGE), }); this.totalAbsorbed = 0; } get suggestionThresholdsEfficiency() { return { actual: 1 - this.wastedCasts / this.casts, isLessThan: { minor: 0.95, average: 0.9, major: .8, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholdsEfficiency) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You casted {this.wastedCasts} <SpellLink id={SPELLS.TOMBSTONE_TALENT.id} /> with less than 5 charges causing a reduced absorb shield.</>) .icon(SPELLS.TOMBSTONE_TALENT.icon) .actual(`${formatPercentage(actual)}% bad Tombstone casts`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <TalentStatisticBox talent={SPELLS.TOMBSTONE_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(3)} value={this.wastedCasts} label="Bad Casts" tooltip="Any cast without 5 charges is considered a wasted cast." > <table className="table table-condensed"> <thead> <tr> <th>Charges</th> <th>RP Wasted</th> <th>Absorb Used (%)</th> </tr> </thead> <tbody> {Object.values(this.tombstone).map((e, i) => ( <tr key={i}> <th>{this.tombstone[i].charges}</th> <td> <TooltipElement content={<><strong>RP Generated:</strong> {this.tombstone[i].rpGained - this.tombstone[i].rpWasted}</>}> {this.tombstone[i].rpWasted} </TooltipElement> </td> <td> <TooltipElement content={( <> <strong>Damage Absorbed:</strong> {formatNumber(this.tombstone[i].totalAbsorbed)} <br /> <strong>Absorb Shield: </strong> {formatNumber(this.tombstone[i].absorbSize)} <br /> <strong>Healing: </strong> {this.owner.formatItemHealingDone(this.tombstone[i].totalAbsorbed)} </> )} > {formatPercentage(this.tombstone[i].totalAbsorbed / this.tombstone[i].absorbSize)}% </TooltipElement> </td> </tr> ))} </tbody> </table> </TalentStatisticBox> ); } } export default Tombstone;
src/components/Header/Header.js
tinwaisi/take-home
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import logoUrl from './logo-small.png'; import logoUrl2x from './logo-small@2x.png'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <div className={s.banner}> <h2 className={s.bannerTitle}>Movies</h2> </div> </div> </div> ); } } export default withStyles(s)(Header);
modules/experiences/client/components/create-experience/Report.js
Trustroots/trustroots
// External dependencies import { useTranslation } from 'react-i18next'; import PropTypes from 'prop-types'; import React from 'react'; import styled from 'styled-components'; // Internal dependencies import '@/config/client/i18n'; import Switch from '@/modules/core/client/components/Switch'; const ReportContainer = styled.div` margin-top: 50px; `; export default function Report({ onChangeReport, onChangeReportMessage, report, reportMessage, }) { const { t } = useTranslation('experiences'); return ( <ReportContainer> <p> {t( "It's extremely important you report anyone behaving against community rules or values to us.", )} </p> <Switch isSmall checked={report} onChange={onChangeReport}> {t('Privately report this person to the moderators')} </Switch> {report && ( <> <br /> <br /> <label htmlFor="report-message" className="control-label"> {t('Message to the moderators')} </label> <textarea className="form-control input-lg" rows="7" id="report-message" onChange={event => onChangeReportMessage(event.target.value)} value={reportMessage} ></textarea> <span className="help-block"> {t('Please write in English if possible, thank you.')} <br /> </span> </> )} </ReportContainer> ); } Report.propTypes = { report: PropTypes.bool.isRequired, reportMessage: PropTypes.string.isRequired, onChangeReport: PropTypes.func.isRequired, onChangeReportMessage: PropTypes.func.isRequired, };
src/components/category/category-list.js
chemoish/react-webpack
import React from 'react'; import Reflux from 'reflux'; import CategoryList from './component/_category-list.js'; import CategoryListDomainAction from './store/category-list-domain-action.js'; import CategoryListDomainStore from './store/category-list-domain-store.js'; export default React.createClass({ mixins: [Reflux.connect(CategoryListDomainStore, 'categories')], componentDidMount() { CategoryListDomainAction.load(); }, render() { return ( <div> <h1>Categories</h1> <CategoryList categories={this.state.categories} /> </div> ); } });
assets/jqwidgets/demos/react/app/bulletchart/righttoleftlayout/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxBulletChart from '../../../jqwidgets-react/react_jqxbulletchart.js'; class App extends React.Component { render() { let ranges = [ { startValue: 0, endValue: 200, color: '#000000', opacity: 0.5 }, { startValue: 200, endValue: 250, color: '#000000', opacity: 0.3 }, { startValue: 250, endValue: 300, color: '#000000', opacity: 0.1 } ]; let pointer = { value: 270, label: 'Revenue 2014 YTD', size: '25%', color: 'Black' }; let target = { value: 260, label: 'Revenue 2013 YTD', size: 4, color: 'Black' }; let ticks = { position: 'both', interval: 50, size: 10 }; return ( <JqxBulletChart width={500} height={80} barSize={'40%'} ranges={ranges} ticks={ticks} title={'Revenue 2014 YTD'} description={'(U.S. $ in thousands)'} rtl={true} pointer={pointer} target={target} labelsFormat={'c'} showTooltip={true} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/routes/dashboard/index.js
medevelopment/updatemeadmin
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Dashboard from './Dashboard'; import Layout from '../../components/Layout'; export default { path: '/dashboard', async action({ fetch }) { const resp = await fetch('/graphql', { body: JSON.stringify({ query: '{news{title,link,content}}', }), }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Layout><Dashboard /></Layout>, }; }, };
src/routes/about/index.js
DaveyEdwards/myiworlds
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import { graphql } from 'relay-runtime'; import Layout from '../../components/Layout'; import Page from '../../components/Page'; export default { path: '/about', async action({ api }) { const [data, page] = await Promise.all([ api.fetchQuery(graphql` query aboutQuery { me { ...Layout_me } } `), require.ensure([], require => require('./about.md'), 'about'), ]); return { title: page.title, chunk: 'about', component: ( <Layout me={data.me}> <Page {...page} /> </Layout> ), }; }, };
.structor/src/MouseButtonsOverlay.js
ipselon/structor-meta
import React, { Component } from 'react'; class MouseButtonsOverlay extends Component { constructor (props) { super(props); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMouseOut = this.handleMouseOut.bind(this); this.handleContextMenu = this.handleContextMenu.bind(this); this.handleClearMousePosition = this.handleClearMousePosition.bind(this); this.handleSelectParent = this.handleSelectParent.bind(this); this.handleBefore = this.handleBefore.bind(this); this.handleFirst = this.handleFirst.bind(this); this.handleLast = this.handleLast.bind(this); this.handleAfter = this.handleAfter.bind(this); this.handleReplace = this.handleReplace.bind(this); this.handleCut = this.handleCut.bind(this); this.handleCopy = this.handleCopy.bind(this); this.handleClone = this.handleClone.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentDidMount () { const {context} = this.props; if (context) { context.addListener('mouseDown.mousebuttons', (e) => {this.setPosition(e);}); } } componentWillUnmount () { this.$DOMNode = undefined; const {context} = this.props; if (context) { context.removeListener('mouseDown.mousebuttons'); } } setPosition (e) { const {pageX, pageY, button} = e; this.setState({ showMenu: true, mousePos: {pageX, pageY, button}, }); // const validMousePos = mousePos || lastMousePos; // let centerPointX; // let centerPointY; // if (validMousePos && !isMultipleSelected && showBlueprintButtons) { // const topLeftY = newPos.top; // const topLeftX = newPos.left; // const bottomRightY = topLeftY + newPos.height; // const bottomRightX = topLeftX + newPos.width; // if (validMousePos.pageX > topLeftX && // validMousePos.pageX < bottomRightX && // validMousePos.pageY > topLeftY && // validMousePos.pageY < bottomRightY) { // centerPointX = validMousePos.pageX - topLeftX; // centerPointY = validMousePos.pageY - topLeftY; // } else { // if (topLeftY > 40) { // centerPointY = newPos.height / 2; // } else { // centerPointY = 35; // } // if (topLeftX > 60) { // centerPointX = newPos.width / 2; // } else { // centerPointX = 60; // } // } // } } handleMouseOver (e) { // this.props.onMouseOver(e); } handleMouseOut (e) { // this.props.onMouseOut(e); } handleContextMenu (e) { e.preventDefault(); e.stopPropagation(); } handleSelectParent (e) { const {selectedKey, initialState: {onSelectParent}} = this.props; if (onSelectParent) { e.preventDefault(); e.stopPropagation(); onSelectParent(selectedKey, e.metaKey || e.ctrlKey); } } handleBefore (e) { const {selectedKey, initialState: {onBefore}} = this.props; if (onBefore) { e.preventDefault(); e.stopPropagation(); onBefore(selectedKey, e.metaKey || e.ctrlKey); } } handleFirst (e) { const {selectedKey, initialState: {onFirst}} = this.props; if (onFirst) { e.preventDefault(); e.stopPropagation(); onFirst(selectedKey, e.metaKey || e.ctrlKey); } } handleLast (e) { const {selectedKey, initialState: {onLast}} = this.props; if (onLast) { e.preventDefault(); e.stopPropagation(); onLast(selectedKey, e.metaKey || e.ctrlKey); } } handleAfter (e) { const {selectedKey, initialState: {onAfter}} = this.props; if (onAfter) { e.preventDefault(); e.stopPropagation(); onAfter(selectedKey, e.metaKey || e.ctrlKey); } } handleReplace (e) { const {selectedKey, initialState: {onReplace}} = this.props; if (onReplace) { e.preventDefault(); e.stopPropagation(); onReplace(selectedKey, e.metaKey || e.ctrlKey); } } handleCut (e) { const {selectedKey, initialState: {onCut}} = this.props; if (onCut) { e.preventDefault(); e.stopPropagation(); onCut(selectedKey, e.metaKey || e.ctrlKey); } } handleCopy (e) { const {selectedKey, initialState: {onCopy}} = this.props; if (onCopy) { e.preventDefault(); e.stopPropagation(); onCopy(selectedKey, e.metaKey || e.ctrlKey); } } handleClone (e) { const {selectedKey, initialState: {onClone}} = this.props; if (onClone) { e.preventDefault(); e.stopPropagation(); onClone(selectedKey, e.metaKey || e.ctrlKey); } } handleDelete (e) { const {selectedKey, initialState: {onDelete}} = this.props; if (onDelete) { e.preventDefault(); e.stopPropagation(); onDelete(selectedKey, e.metaKey || e.ctrlKey); } } handleClearMousePosition (e) { // this.props.onClearMousePosition(); } render () { const {showMenu} = this.state; if (!showMenu) { return null; } const {centerPointY, centerPointX, componentName, isOverlay} = this.props; let titleStyle = {}; if (isOverlay) { titleStyle.backgroundColor = '#35b3ee'; titleStyle.opacity = 1; } return ( <div className="structor_mouse-center-point" style={{top: centerPointY, left: centerPointX}} onContextMenu={this.handleContextMenu} > <div className="structor_mouse-title" style={titleStyle} > <span>{componentName}</span> </div> <div className="structor_mouse-top-left-second-btn structor_mouse-rectangle-btn umy-icon-cancel-circle" onClick={this.handleClearMousePosition} > </div> <div className="structor_mouse-top-left-btn structor_mouse-rectangle-btn umy-icon-arrow-up-left" title="Select parent component" onClick={this.handleSelectParent} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} > </div> <div className="structor_mouse-top-center-btn structor_mouse-circle-btn umy-icon-arrow-plus-down" title="Append before selected" onClick={this.handleBefore} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-top-right-btn structor_mouse-circle-btn umy-icon-replace" title="Replace selected" onClick={this.handleReplace} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-right-center-btn structor_mouse-circle-btn umy-icon-arrow-plus-down structor_rotate-clockwise" title="Insert into selected as last child" onClick={this.handleReplace} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-bottom-right-btn structor_mouse-rectangle-btn umy-icon-cut" title="Cut selected into clipboard" onClick={this.handleCut} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-bottom-center-btn structor_mouse-circle-btn umy-icon-arrow-plus-up" title="Append after selected" onClick={this.handleAfter} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-bottom-left-btn structor_mouse-rectangle-btn umy-icon-copy" title="Copy selected into clipboard" onClick={this.handleCopy} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-bottom-left-second-btn structor_mouse-rectangle-btn umy-icon-duplicate" title="Clone selected" onClick={this.handleClone} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-left-center-btn structor_mouse-circle-btn umy-icon-arrow-plus-up structor_rotate-clockwise" title="Insert into selected as first child" onClick={this.handleFirst} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> <div className="structor_mouse-left-center-second-btn structor_mouse-rectangle-btn umy-icon-delete structor_mouse-button-warning" title="Delete selected" onClick={this.handleDelete} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} /> </div> ); } } export default MouseButtonsOverlay;
src/instructions/HowItWorks.react.js
DhammaLuke/citybook
import React, { Component } from 'react'; import Row from 'react-bootstrap/lib/Row'; import Col from 'react-bootstrap/lib/Col'; import '../../styles/instructions.scss'; export default class HowItWorks extends Component { render() { return ( <section className="how-it-works"> <Row> <Col md={6} mdOffset={3}> <h2 id="how-it-works" className="text-center">How it works:</h2> <h3>No sign-up, no cost. Start building a contact list that your team will love in 2 minutes or less.</h3> </Col> </Row> <Row> <Col md={8} mdOffset={2}> <object type="image/svg+xml" className="img-responsive diagram" data="../../img/how-it-works.svg"> <img src="../../img/how-it-works.png" alt="No SVG support"/> </object> </Col> </Row> </section> ); } }
App/Components/ChatPage.js
OUCHUNYU/Ralli
import groupsApi from'../Utils/groupsApi.js' import usersApi from'../Utils/usersApi.js' import Firebase from 'firebase' import React, { Component } from 'react'; import { StyleSheet, Text, AlertIOS, ListView, View, TextInput, TouchableHighlight, Image, } from 'react-native'; let styles = StyleSheet.create({ container: { flex: 1 }, button: { height: 60, backgroundColor: '#6600ff', flex: 3, alignItems: 'center', justifyContent: 'center' }, searchInput: { height: 60, padding: 10, fontSize: 18, color: '#111', flex: 10 }, rowContainer: { flexDirection: 'row', padding: 10, marginBottom: 5, }, footerContainer: { backgroundColor: '#E3E3E3', alignItems: 'center', flexDirection: 'row' }, plusButton: { flexDirection: 'row', backgroundColor: '#6600ff', alignItems: 'center', justifyContent: 'center', width: 40, height: 40, borderRadius: 20, borderColor: 'white', borderWidth: 1.5 }, buttonText: { fontSize: 20, color: 'white' }, pluscontainer: { flexDirection: 'row', paddingTop: 65, paddingBottom: 0, justifyContent: 'flex-end', alignItems: 'flex-end' }, avatar: { height: 50, width: 50, borderRadius: 25, }, messageStyle: { marginTop: 15, flex: 1, }, errorMessage: { fontSize: 14, color: '#4d0000', } }); class ChatPage extends Component{ constructor(props){ super(props); this.chatRef = new Firebase('https://ralli.firebaseio.com/groups/' + this.props.groupData.id + "/chatroom"); this.ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}) this.state = { dataSource: this.ds.cloneWithRows([{username: "Ralli Robot", message: "No body has said anything yet, be the first one!", avatarUrl: "http://www.gravatar.com/avatar/04da6ee5653a27ae038bebcdff7ea49c?s=90&r=g"}]), items: [], message: '', error: false, userName: '' } } componentWillMount(){ this.chatRef.on('value', function(snapshot) { if(snapshot.val()) { let messages = []; for(var i in snapshot.val()) { messages.push(snapshot.val()[i]); } messages = messages.reverse(); this.setState({ items: messages, dataSource: this.ds.cloneWithRows(messages), userName: this.props.userData.username }); }else { this.setState({ userName: this.props.userData.username }); } }.bind(this)); } saveResponse(promptValue){ // api call to add user to current chat this.setState({ promptValue: promptValue }) let personEmail = this.state.promptValue; usersApi.getUserByEmail(personEmail).then((res) => { // user id is Object.keys(res.val())[0] // group id is this. groupsApi.joinGroup(this.props.groupData.id, Object.keys(res.val())[0], this.props.groupData.name); }).catch((err) => { this.setState({ error: "User Not Found" }) }) } handleChange(e){ this.setState({ message: e.nativeEvent.text, error: false }) } handleSubmit(){ this.chatRef.push({ username: this.state.userName, message: this.state.message || '', avatarUrl: this.props.userData.avatarUrl }); this.setState({ message: '' }) } renderRow(rowData){ return ( <View style={styles.rowContainer}> <Image style={styles.avatar} source={{uri: rowData.avatarUrl}} /> <Text style={styles.messageStyle} > {rowData.username}: {rowData.message}</Text> </View> ); } footer() { return ( <View style={styles.footerContainer}> <TextInput style={styles.searchInput} value={this.state.message} onChange={this.handleChange.bind(this)} placeholder="Group Chat" /> <TouchableHighlight style={styles.button} onPress={this.handleSubmit.bind(this)} underlayColor="#88D4F5"> <Text style={styles.buttonText}>Submit</Text> </TouchableHighlight> </View> ) } render() { let showErr = this.state.error ? <Text style={styles.errorMessage}> {this.state.error} </Text> : <View></View> return ( <View style={styles.container}> <View style={styles.pluscontainer}> {showErr} <TouchableHighlight style={styles.plusButton} onPress={() => AlertIOS.prompt('Add a person by Email', null, this.saveResponse.bind(this))} underlayColor='black'> <Text style={styles.buttonText}> + </Text> </TouchableHighlight> </View> <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} /> {this.footer()} </View> ) } }; ChatPage.propTypes = { groupData: React.PropTypes.object.isRequired, userData: React.PropTypes.object.isRequired }; module.exports = ChatPage;
src/components/Carousel/Carousel.js
sprakash1993/NVSApp
import React, { Component } from 'react'; import { Carousel, CarouselItem, CarouselControl, CarouselIndicators, CarouselCaption } from 'reactstrap'; const items = [ { src: 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15ba800aa1d%20text%20%7B%20fill%3A%23555%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15ba800aa1d%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22285.921875%22%20y%3D%22218.3%22%3EFirst%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E', altText: 'Slide 1', caption: 'Slide 1' }, { src: 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15ba800aa20%20text%20%7B%20fill%3A%23444%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15ba800aa20%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23666%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22247.3203125%22%20y%3D%22218.3%22%3ESecond%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E', altText: 'Slide 2', caption: 'Slide 2' }, { src: 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22800%22%20height%3D%22400%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20800%20400%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15ba800aa21%20text%20%7B%20fill%3A%23333%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A40pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15ba800aa21%22%3E%3Crect%20width%3D%22800%22%20height%3D%22400%22%20fill%3D%22%23555%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22277%22%20y%3D%22218.3%22%3EThird%20slide%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E', altText: 'Slide 3', caption: 'Slide 3' } ]; class Example extends Component { constructor(props) { super(props); this.state = { activeIndex: 0 }; this.next = this.next.bind(this); this.previous = this.previous.bind(this); this.goToIndex = this.goToIndex.bind(this); this.onExiting = this.onExiting.bind(this); this.onExited = this.onExited.bind(this); } onExiting() { this.animating = true; } onExited() { this.animating = false; } next() { if (this.animating) return; const nextIndex = this.state.activeIndex === items.length - 1 ? 0 : this.state.activeIndex + 1; this.setState({ activeIndex: nextIndex }); } previous() { if (this.animating) return; const nextIndex = this.state.activeIndex === 0 ? items.length - 1 : this.state.activeIndex - 1; this.setState({ activeIndex: nextIndex }); } goToIndex(newIndex) { if (this.animating) return; this.setState({ activeIndex: newIndex }); } render() { const { activeIndex } = this.state; const slides = items.map((item) => { return ( <CarouselItem onExiting={this.onExiting} onExited={this.onExited} key={item.src} src={item.src} altText={item.altText} > <CarouselCaption captionText={item.caption} captionHeader={item.caption} /> </CarouselItem> ); }); return ( <Carousel activeIndex={activeIndex} next={this.next} previous={this.previous} > <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} /> {slides} <CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} /> <CarouselControl direction="next" directionText="Next" onClickHandler={this.next} /> </Carousel> ); } } export default Example;
zwdemoRect/src/index.js
send2ocean/nodelearn
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; ReactDOM.render( <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}> <App /> </MuiThemeProvider> , document.getElementById('root') );
src/containers/HomePage.js
wilsonkv/mock-project
import React, { Component } from 'react'; import { connect } from 'react-redux'; import FontIcon from 'react-md/lib/FontIcons'; import PropTypes from 'prop-types'; import TextField from 'react-md/lib/TextFields'; import Loader from 'react-loader'; import { Card, CardTitle, CardText } from 'react-md'; import { fetchAllUsers } from '../store/user/actions'; import '../assets/stylesheets/HomePage.scss'; const style = { maxWidth: 800 }; export class HomePage extends Component { constructor(props) { super(props); } //Similar like pageLoad event componentDidMount() { this.props.dispatch(fetchAllUsers()); } renderUsers(users) { if (!users.length) { return <div id="home-page__null-state">No data available currently!</div>; } return ( <div className="list"> {users.map(user => { return ( <div> <Card style={style} className="md-block-centered"> <CardTitle title={`${user.firstName} ${user.lastName}`} subtitle={`${user.email} | ${user.location}`} /> <CardText>{user.aboutMe}</CardText> </Card> <br /> </div> ); })} </div> ); } render() { return ( <div className="page-wrapper"> <div className="page"> <Loader color="#fff" loaded={!this.props.loading}> <div id="home-page__null-state"> {this.renderUsers(this.props.users)} </div> </Loader> </div> </div> ); } } HomePage.propTypes = { dispatch: PropTypes.func.isRequired, users: PropTypes.array, }; function mapStateToProps(state) { return { users: state.user.users, loading: state.user.loading, }; } export default connect(mapStateToProps)(HomePage);
jenkins-design-language/src/js/components/material-ui/svg-icons/av/library-music.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvLibraryMusic = (props) => ( <SvgIcon {...props}> <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 5h-3v5.5c0 1.38-1.12 2.5-2.5 2.5S10 13.88 10 12.5s1.12-2.5 2.5-2.5c.57 0 1.08.19 1.5.51V5h4v2zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6z"/> </SvgIcon> ); AvLibraryMusic.displayName = 'AvLibraryMusic'; AvLibraryMusic.muiName = 'SvgIcon'; export default AvLibraryMusic;
src/index.js
bedoherty/NameGame
import React from 'react'; import ReactDOM from 'react-dom'; // Import our components import Window from './components/Window'; import './index.css'; ReactDOM.render( <Window />, document.getElementById('root') );
examples/js/column/column-style-table.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'The white-space property specifies how white-space inside an element is handled, default is normal ' + id, price: 2100 + i }); } } addProducts(5); export default class ColumnStyleTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' tdStyle={ { whiteSpace: 'normal' } }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' thStyle={ { 'fontWeight': 'lighter' } }>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
app/javascript/mastodon/components/relative_timestamp.js
WitchesTown/mastodon
import React from 'react'; import { injectIntl, defineMessages } from 'react-intl'; import PropTypes from 'prop-types'; const messages = defineMessages({ just_now: { id: 'relative_time.just_now', defaultMessage: 'now' }, seconds: { id: 'relative_time.seconds', defaultMessage: '{number}s' }, minutes: { id: 'relative_time.minutes', defaultMessage: '{number}m' }, hours: { id: 'relative_time.hours', defaultMessage: '{number}h' }, days: { id: 'relative_time.days', defaultMessage: '{number}d' }, }); const dateFormatOptions = { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', }; const shortDateFormatOptions = { month: 'numeric', day: 'numeric', }; const SECOND = 1000; const MINUTE = 1000 * 60; const HOUR = 1000 * 60 * 60; const DAY = 1000 * 60 * 60 * 24; const MAX_DELAY = 2147483647; const selectUnits = delta => { const absDelta = Math.abs(delta); if (absDelta < MINUTE) { return 'second'; } else if (absDelta < HOUR) { return 'minute'; } else if (absDelta < DAY) { return 'hour'; } return 'day'; }; const getUnitDelay = units => { switch (units) { case 'second': return SECOND; case 'minute': return MINUTE; case 'hour': return HOUR; case 'day': return DAY; default: return MAX_DELAY; } }; @injectIntl export default class RelativeTimestamp extends React.Component { static propTypes = { intl: PropTypes.object.isRequired, timestamp: PropTypes.string.isRequired, }; state = { now: this.props.intl.now(), }; shouldComponentUpdate (nextProps, nextState) { // As of right now the locale doesn't change without a new page load, // but we might as well check in case that ever changes. return this.props.timestamp !== nextProps.timestamp || this.props.intl.locale !== nextProps.intl.locale || this.state.now !== nextState.now; } componentWillReceiveProps (nextProps) { if (this.props.timestamp !== nextProps.timestamp) { this.setState({ now: this.props.intl.now() }); } } componentDidMount () { this._scheduleNextUpdate(this.props, this.state); } componentWillUpdate (nextProps, nextState) { this._scheduleNextUpdate(nextProps, nextState); } componentWillUnmount () { clearTimeout(this._timer); } _scheduleNextUpdate (props, state) { clearTimeout(this._timer); const { timestamp } = props; const delta = (new Date(timestamp)).getTime() - state.now; const unitDelay = getUnitDelay(selectUnits(delta)); const unitRemainder = Math.abs(delta % unitDelay); const updateInterval = 1000 * 10; const delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder); this._timer = setTimeout(() => { this.setState({ now: this.props.intl.now() }); }, delay); } render () { const { timestamp, intl } = this.props; const date = new Date(timestamp); const delta = this.state.now - date.getTime(); let relativeTime; if (delta < 10 * SECOND) { relativeTime = intl.formatMessage(messages.just_now); } else if (delta < 3 * DAY) { if (delta < MINUTE) { relativeTime = intl.formatMessage(messages.seconds, { number: Math.floor(delta / SECOND) }); } else if (delta < HOUR) { relativeTime = intl.formatMessage(messages.minutes, { number: Math.floor(delta / MINUTE) }); } else if (delta < DAY) { relativeTime = intl.formatMessage(messages.hours, { number: Math.floor(delta / HOUR) }); } else { relativeTime = intl.formatMessage(messages.days, { number: Math.floor(delta / DAY) }); } } else { relativeTime = intl.formatDate(date, shortDateFormatOptions); } return ( <time dateTime={timestamp} title={intl.formatDate(date, dateFormatOptions)}> {relativeTime} </time> ); } }
dayangWeb/src/containers/AppContainer.js
dianziguan1234/React
import { connect } from 'react-redux' import React, { Component } from 'react'; import Home from '../components/HomePage' import {btnClick} from '../actions/BtnClickAction' // var Home = React.createClass({ // render:function() { // console.info("HomeState") // console.info("HomeState",this.props.HomeState) // console.info("HomeState",this.props.HomeDispatch) // return ( // <span> // woshiyigehaoren // </span> // ) // } // }) const mapStateToProps = (state) => ({ HomeState:state }) const mapDispatchToProps = (dispatch) => ({ HomeDispatch:(userName,passWord,json,isLogined) =>{ dispatch(btnClick(userName,passWord,json,isLogined)) } }) export default connect ( mapStateToProps, mapDispatchToProps )(Home)
fixtures/flight/src/index.js
ericyang321/react
import React from 'react'; import ReactDOM from 'react-dom'; import ReactTransportDOMClient from 'react-transport-dom-webpack'; import App from './App'; let data = ReactTransportDOMClient.createFromFetch( fetch('http://localhost:3001') ); ReactDOM.render(<App data={data} />, document.getElementById('root'));
src/components/AthletePage.js
pneiman1/react-athlete-medals-app
import React from 'react'; import { Link } from 'react-router-dom'; import { AthletesMenu } from './AthletesMenu'; import { Medal } from './Medal'; import { Flag } from './Flag'; export const AthletePage = ({ athlete, athletes }) => { const headerStyle = { backgroundImage: `url(/img/${athlete.cover})` }; return ( <div className="athlete-full"> <AthletesMenu athletes={athletes} /> <div className="athlete"> <header style={headerStyle} /> <div className="picture-container"> <img alt={`${athlete.name}'s profile`} src={`/img/${athlete.image}`} /> <h2 className="name">{athlete.name}</h2> </div> <section className="description"> Olympic medalist from &nbsp;<strong><Flag {...athlete.country} showName="true" /></strong>, born in {athlete.birth} (Find out more on <a href={athlete.link}>Wikipedia</a>). </section> <section className="medals"> <p>Winner of <strong>{athlete.medals.length}</strong> medals:</p> <ul>{ athlete.medals.map(medal => <Medal key={medal.id} {...medal} />) }</ul> </section> </div> <div className="navigateBack"> <Link to="/">« Back to the index</Link> </div> </div> ); }; export default AthletePage;
fixtures/packaging/systemjs-builder/dev/input.js
facebook/react
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
src/svg-icons/maps/navigation.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsNavigation = (props) => ( <SvgIcon {...props}> <path d="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z"/> </SvgIcon> ); MapsNavigation = pure(MapsNavigation); MapsNavigation.displayName = 'MapsNavigation'; MapsNavigation.muiName = 'SvgIcon'; export default MapsNavigation;
src/components/common/svg-icons/communication/voicemail.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationVoicemail = (props) => ( <SvgIcon {...props}> <path d="M18.5 6C15.46 6 13 8.46 13 11.5c0 1.33.47 2.55 1.26 3.5H9.74c.79-.95 1.26-2.17 1.26-3.5C11 8.46 8.54 6 5.5 6S0 8.46 0 11.5 2.46 17 5.5 17h13c3.04 0 5.5-2.46 5.5-5.5S21.54 6 18.5 6zm-13 9C3.57 15 2 13.43 2 11.5S3.57 8 5.5 8 9 9.57 9 11.5 7.43 15 5.5 15zm13 0c-1.93 0-3.5-1.57-3.5-3.5S16.57 8 18.5 8 22 9.57 22 11.5 20.43 15 18.5 15z"/> </SvgIcon> ); CommunicationVoicemail = pure(CommunicationVoicemail); CommunicationVoicemail.displayName = 'CommunicationVoicemail'; CommunicationVoicemail.muiName = 'SvgIcon'; export default CommunicationVoicemail;
src/routes.js
wenjiezhang2013/react_learn
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/svg-icons/device/screen-lock-landscape.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenLockLandscape = (props) => ( <SvgIcon {...props}> <path d="M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2v1h-2.4v-1z"/> </SvgIcon> ); DeviceScreenLockLandscape = pure(DeviceScreenLockLandscape); DeviceScreenLockLandscape.displayName = 'DeviceScreenLockLandscape'; DeviceScreenLockLandscape.muiName = 'SvgIcon'; export default DeviceScreenLockLandscape;
app/js/index.js
workco/hackathon-talent
'use strict'; import React from 'react'; import Router from 'react-router'; import routes from './Routes'; if(process.env.NODE_ENV !== 'production' ) { // Enable React devtools window.React = React; } Router.run(routes, Router.HistoryLocation, function(Handler, state) { React.render(<Handler params={state.params} query={state.query} />, document.getElementById('app')); });
js/components/poeme_details/index.js
Rebaiahmed/Alchaaer
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import { Container, Header, Title, Right, List, ListItem,InputGroup, Input ,Picker,Badge,H3, Fab,Content, Card, CardItem, Thumbnail, Text, Button, Icon, Left, Body} from 'native-base'; import {Column as Col, Row} from 'react-native-flexbox-grid'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; class PoemeDetailsPage extends Component { constructor(props) { super(props); this.state={ Article :{} } console.log("propos"+ this.props.titre); var myFirebaseRef = new Firebase('https://react-native-login-app.firebaseio.com'); this.articleRef = myFirebaseRef.child(this.props.titre); //console.log("Article is"+ this.articleRef.equalTo('Article1')); } //**********add to Favorites***********// addFavorites() { console.log("iic add to favorite"); } //******************load Article*************// loadArticle(article) { var myFirebaseRef = new Firebase('https://react-native-login-app.firebaseio.com'); this.articleRef = myFirebaseRef.child(article); //console.log("Article load is"+ this.articleRef.equalTo('Article1')); //var data =this.articleRef.orderByChild('word').equalTo('noun') this.articleRef.on('value', (snap) => { // get children as an array //console.log("the snap is"+ JSON.stringify(snap)); this.setState({Article :snap }) }) } //*********************************// loadArticleV2(article) { var myFirebaseRef = new Firebase('https://react-native-login-app.firebaseio.com'); this.articlesRef = myFirebaseRef.child("articles"); console.log("artciles"+ this.articlesRef); var article = this.articlesRef.equalTo('Article1'); console.log("arrara "+ article); this.articlesRef.on('value', (snap) => { // get children as an array console.log("snam"+ snap.val() + " Title " +snap.val().Title ); var newPost = snap.val(); console.log("snap"+ newPost.Title + "ocntent"+ newPost.content + "dd" + newPost.Content); snap.forEach((child) => { console.log(child.key()+": "+child.val().Title + "con" ); this.setState({ Article :{ Title : child.val().Title } }) /*items.push({ title: child.val().title, desc: child.val().desc, _key: child.key });ù*/ }) }); console.log("state article is"+this.state.Article); } //*****************************// componentDidMount() { this.loadArticle(this.props.titre); console.log("state article is"+this.state.Article); this.loadArticleV2(this.props.titre); } static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, } render() { const { props: { name, index, list } } = this; return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="ios-arrow-back" /> </Button> </Left> <Body> <Title>{(name) ? this.props.name : 'الشعر العربي '}</Title> </Body> <Right> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Right> </Header> <Content padder> <Card > <CardItem> <Left> <Thumbnail source={require('../../../images/component_poemes/alchaerealarabi.jpg')} /> <Body> <Text>{ this.state.Article.Title }</Text> <Text note>GeekyAnts</Text> </Body> </Left> </CardItem> <CardItem cardBody> </CardItem> <CardItem content> <Text>Wait a minute. Wait a minute, Doc. Uhhh... Are you telling me that you built a time machine... out of a DeLorean?! Whoa. This is heavy.</Text> </CardItem> </Card> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(PoemeDetailsPage);
packages/ringcentral-widgets-docs/src/app/pages/Components/Footer/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/Footer'; const FooterPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="Footer" description={info.description} /> <CodeExample code={demoCode} title="Footer Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default FooterPage;
application/3-react/js/app.js
bishopZ/Sandbox
import React from 'react'; import { render } from 'react-dom'; import { HashRouter as Router, Route } from 'react-router-dom'; import { Provider, connect } from 'react-redux'; import { ConnectedRouter } from 'connected-react-router'; import { history, store } from './database/store.js'; import * as Actions from './database/actions.js'; import NavBar from './components/navbar.js'; import HomePage from './pages/home.js'; import AboutPage from './pages/about.js'; import BlogPage from './pages/blog.js'; // simple way to create pass-along redux containers const defaultMapStateToProps = (a)=>(a); // give them everything const defaultMapDispatchToProps = Actions; // give them everything const container = (Page) => { return connect( defaultMapStateToProps, // which properties are sent to the page defaultMapDispatchToProps // which functions are sent to the page )(Page); }; // render the router render( <Provider store={store}> <ConnectedRouter history={history}> <Router> <div> <NavBar /> <Route exact path="/" component={container(HomePage)}/> <Route exact path="/about" component={container(AboutPage)}/> <Route exact path="/blog" component={container(BlogPage)}/> </div> </Router> </ConnectedRouter> </Provider>, document.getElementById('react-root') ); // it has begun console.log('%c App Started', 'color:green');
frontend/js/components/organisms/RadioButtons.js
ttavenner/okcandidate-platform
'use strict'; import React, { Component } from 'react'; import RadioButton from './../molecules/RadioButton'; import PropTypes from 'prop-types'; class RadioButtons extends Component { render() { return ( <div className="radio-buttons"> { !this.props.hideName && <label>{this.props.name}</label> } { this.props.options.map((item, index) => { const label = item[this.props.labelKey] || item.name; return ( <RadioButton onChange={this.props.onChange} checked={item.id === this.props.selected} key={index} id={item.id} label={label} name={this.props.name} /> ); }) } { this.props.help && <div className="radio-buttons-help"> <span>{this.props.help}</span> </div> } { this.props.error && <div className="radio-buttons-error"> <span>{this.props.error}</span> </div> } </div> ); } } RadioButtons.propTypes = { name: PropTypes.string, labelKey: PropTypes.string, options: PropTypes.array, selected: PropTypes.number, onChange: PropTypes.func, help: PropTypes.string, error: PropTypes.string, hideName: PropTypes.bool }; export default RadioButtons;
app/javascript/mastodon/features/account/components/header.js
rainyday/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Button from 'mastodon/components/button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { autoPlayGif, me, isStaff } from 'mastodon/initial_state'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import Avatar from 'mastodon/components/avatar'; import { shortNumberFormat } from 'mastodon/utils/numbers'; import { NavLink } from 'react-router-dom'; import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container'; const messages = defineMessages({ unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, follow: { id: 'account.follow', defaultMessage: 'Follow' }, cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Cancel follow request' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, linkVerifiedOn: { id: 'account.link_verified_on', defaultMessage: 'Ownership of this link was checked on {date}' }, account_locked: { id: 'account.locked_info', defaultMessage: 'This account privacy status is set to locked. The owner manually reviews who can follow them.' }, mention: { id: 'account.mention', defaultMessage: 'Mention @{name}' }, direct: { id: 'account.direct', defaultMessage: 'Direct message @{name}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, report: { id: 'account.report', defaultMessage: 'Report @{name}' }, share: { id: 'account.share', defaultMessage: 'Share @{name}\'s profile' }, media: { id: 'account.media', defaultMessage: 'Media' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, hideReblogs: { id: 'account.hide_reblogs', defaultMessage: 'Hide boosts from @{name}' }, showReblogs: { id: 'account.show_reblogs', defaultMessage: 'Show boosts from @{name}' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Blocked domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, endorse: { id: 'account.endorse', defaultMessage: 'Feature on profile' }, unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' }, add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, }); const dateFormatOptions = { month: 'short', day: 'numeric', year: 'numeric', hour12: false, hour: '2-digit', minute: '2-digit', }; export default @injectIntl class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, identity_props: ImmutablePropTypes.list, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, domain: PropTypes.string.isRequired, }; openEditProfile = () => { window.open('/settings/profile', '_blank'); } isStatusesPageActive = (match, location) => { if (!match) { return false; } return !location.pathname.match(/\/(followers|following)\/?$/); } _updateEmojis () { const node = this.node; if (!node || autoPlayGif) { return; } const emojis = node.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; if (emoji.classList.contains('status-emoji')) { continue; } emoji.classList.add('status-emoji'); emoji.addEventListener('mouseenter', this.handleEmojiMouseEnter, false); emoji.addEventListener('mouseleave', this.handleEmojiMouseLeave, false); } } componentDidMount () { this._updateEmojis(); } componentDidUpdate () { this._updateEmojis(); } handleEmojiMouseEnter = ({ target }) => { target.src = target.getAttribute('data-original'); } handleEmojiMouseLeave = ({ target }) => { target.src = target.getAttribute('data-static'); } setRef = (c) => { this.node = c; } render () { const { account, intl, domain, identity_proofs } = this.props; if (!account) { return null; } let info = []; let actionBtn = ''; let lockedIcon = ''; let menu = []; if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) { info.push(<span key='followed_by' className='relationship-tag'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'blocking'])) { info.push(<span key='blocked' className='relationship-tag'><FormattedMessage id='account.blocked' defaultMessage='Blocked' /></span>); } if (me !== account.get('id') && account.getIn(['relationship', 'muting'])) { info.push(<span key='muted' className='relationship-tag'><FormattedMessage id='account.muted' defaultMessage='Muted' /></span>); } else if (me !== account.get('id') && account.getIn(['relationship', 'domain_blocking'])) { info.push(<span key='domain_blocked' className='relationship-tag'><FormattedMessage id='account.domain_blocked' defaultMessage='Domain blocked' /></span>); } if (me !== account.get('id')) { if (!account.get('relationship')) { // Wait until the relationship is loaded actionBtn = ''; } else if (account.getIn(['relationship', 'requested'])) { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.cancel_follow_request)} title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} />; } else if (!account.getIn(['relationship', 'blocking'])) { actionBtn = <Button disabled={account.getIn(['relationship', 'blocked_by'])} className={classNames('logo-button', { 'button--destructive': account.getIn(['relationship', 'following']) })} text={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} />; } else if (account.getIn(['relationship', 'blocking'])) { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.props.onBlock} />; } } else { actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.edit_profile)} onClick={this.openEditProfile} />; } if (account.get('moved') && !account.getIn(['relationship', 'following'])) { actionBtn = ''; } if (account.get('locked')) { lockedIcon = <Icon id='lock' title={intl.formatMessage(messages.account_locked)} />; } if (account.get('id') !== me) { menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.props.onMention }); menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.props.onDirect }); menu.push(null); } if ('share' in navigator) { menu.push({ text: intl.formatMessage(messages.share, { name: account.get('username') }), action: this.handleShare }); menu.push(null); } if (account.get('id') === me) { menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); } else { if (account.getIn(['relationship', 'following'])) { if (!account.getIn(['relationship', 'muting'])) { if (account.getIn(['relationship', 'showing_reblogs'])) { menu.push({ text: intl.formatMessage(messages.hideReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } else { menu.push({ text: intl.formatMessage(messages.showReblogs, { name: account.get('username') }), action: this.props.onReblogToggle }); } } menu.push({ text: intl.formatMessage(account.getIn(['relationship', 'endorsed']) ? messages.unendorse : messages.endorse), action: this.props.onEndorseToggle }); menu.push({ text: intl.formatMessage(messages.add_or_remove_from_list), action: this.props.onAddToList }); menu.push(null); } if (account.getIn(['relationship', 'muting'])) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.props.onMute }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.props.onMute }); } if (account.getIn(['relationship', 'blocking'])) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.props.onBlock }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.props.onBlock }); } menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.props.onReport }); } if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (account.getIn(['relationship', 'domain_blocking'])) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.props.onUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.props.onBlockDomain }); } } if (account.get('id') !== me && isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${account.get('id')}` }); } const content = { __html: account.get('note_emojified') }; const displayNameHtml = { __html: account.get('display_name_html') }; const fields = account.get('fields'); const acct = account.get('acct').indexOf('@') === -1 && domain ? `${account.get('acct')}@${domain}` : account.get('acct'); let badge; if (account.get('bot')) { badge = (<div className='account-role bot'><FormattedMessage id='account.badges.bot' defaultMessage='Bot' /></div>); } else if (account.get('group')) { badge = (<div className='account-role group'><FormattedMessage id='account.badges.group' defaultMessage='Group' /></div>); } else { badge = null; } return ( <div className={classNames('account__header', { inactive: !!account.get('moved') })} ref={this.setRef}> <div className='account__header__image'> <div className='account__header__info'> {info} </div> <img src={autoPlayGif ? account.get('header') : account.get('header_static')} alt='' className='parallax' /> </div> <div className='account__header__bar'> <div className='account__header__tabs'> <a className='avatar' href={account.get('url')} rel='noopener noreferrer' target='_blank'> <Avatar account={account} size={90} /> </a> <div className='spacer' /> <div className='account__header__tabs__buttons'> {actionBtn} <DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' /> </div> </div> <div className='account__header__tabs__name'> <h1> <span dangerouslySetInnerHTML={displayNameHtml} /> {badge} <small>@{acct} {lockedIcon}</small> </h1> </div> <div className='account__header__extra'> <div className='account__header__bio'> { (fields.size > 0 || identity_proofs.size > 0) && ( <div className='account__header__fields'> {identity_proofs.map((proof, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: proof.get('provider') }} /> <dd className='verified'> <a href={proof.get('proof_url')} target='_blank' rel='noopener noreferrer'><span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(proof.get('updated_at'), dateFormatOptions) })}> <Icon id='check' className='verified__mark' /> </span></a> <a href={proof.get('profile_url')} target='_blank' rel='noopener noreferrer'><span dangerouslySetInnerHTML={{ __html: ' '+proof.get('provider_username') }} /></a> </dd> </dl> ))} {fields.map((pair, i) => ( <dl key={i}> <dt dangerouslySetInnerHTML={{ __html: pair.get('name_emojified') }} title={pair.get('name')} /> <dd className={pair.get('verified_at') && 'verified'} title={pair.get('value_plain')}> {pair.get('verified_at') && <span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(pair.get('verified_at'), dateFormatOptions) })}><Icon id='check' className='verified__mark' /></span>} <span dangerouslySetInnerHTML={{ __html: pair.get('value_emojified') }} /> </dd> </dl> ))} </div> )} {account.get('note').length > 0 && account.get('note') !== '<p></p>' && <div className='account__header__content' dangerouslySetInnerHTML={content} />} </div> <div className='account__header__extra__links'> <NavLink isActive={this.isStatusesPageActive} activeClassName='active' to={`/accounts/${account.get('id')}`} title={intl.formatNumber(account.get('statuses_count'))}> <strong>{shortNumberFormat(account.get('statuses_count'))}</strong> <FormattedMessage id='account.posts' defaultMessage='Toots' /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/following`} title={intl.formatNumber(account.get('following_count'))}> <strong>{shortNumberFormat(account.get('following_count'))}</strong> <FormattedMessage id='account.follows' defaultMessage='Follows' /> </NavLink> <NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/followers`} title={intl.formatNumber(account.get('followers_count'))}> <strong>{shortNumberFormat(account.get('followers_count'))}</strong> <FormattedMessage id='account.followers' defaultMessage='Followers' /> </NavLink> </div> </div> </div> </div> ); } }
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
yangchaogit/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import Inputs from 'utils/Inputs'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import ComposeActionCreators from 'actions/ComposeActionCreators'; import GroupStore from 'stores/GroupStore'; import PreferencesStore from 'stores/PreferencesStore'; import ComposeStore from 'stores/ComposeStore'; import AvatarItem from 'components/common/AvatarItem.react'; import MentionDropdown from 'components/common/MentionDropdown.react'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = () => { return { text: ComposeStore.getText(), profile: ActorClient.getUser(ActorClient.getUid()), sendByEnter: PreferencesStore.sendByEnter, mentions: ComposeStore.getMentions() }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); GroupStore.addChangeListener(this.onChange); ComposeStore.addChangeListener(this.onChange); PreferencesStore.addChangeListener(this.onChange); } componentWillUnmount() { GroupStore.removeChangeListener(this.onChange); ComposeStore.removeChangeListener(this.onChange); PreferencesStore.removeChangeListener(this.onChange); } onChange = () => { this.setState(getStateFromStores()); }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } onMessageChange = event => { let text = event.target.value; ComposeActionCreators.onTyping(this.props.peer, text, this.getCaretPosition()); }; onKeyDown = event => { if (this.state.mentions === null) { if (this.state.sendByEnter === 'true') { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } } else { if (event.keyCode === KeyCodes.ENTER && event.metaKey) { event.preventDefault(); this.sendTextMessage(); } } } }; sendTextMessage = () => { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } ComposeActionCreators.cleanText(); }; onSendFileClick = () => { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }; onPhotoInputChange = () => { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; onMentionSelect = (mention) => { ComposeActionCreators.insertMention(this.props.peer, this.state.text, this.getCaretPosition(), mention); this.refs.area.getDOMNode().focus(); }; onMentionClose = () => { ComposeActionCreators.closeMention(); }; getCaretPosition = () => { let el = this.refs.area.getDOMNode(); let selection = Inputs.getInputSelection(el); return selection.start; }; render() { const { text, profile, mentions } = this.state; return ( <section className="compose" onPaste={this.onPaste}> <MentionDropdown mentions={mentions} onSelect={this.onMentionSelect} onClose={this.onMentionClose}/> <AvatarItem className="my-avatar" image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onMessageChange} onKeyDown={this.onKeyDown} value={text} ref="area"/> <footer className="compose__footer row"> <button className="button" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </div> </section> ); } } export default ComposeSection;
src/components/video-list.js
romashka50/ReactReduxModern
import React from 'react'; import VideoItem from './video-list-item'; const VideoList = (props) => { const videoItems = props.videos.map(item => <VideoItem key={item.etag} video={item} onSelectVideo={props.onSelectVideo} />); return ( <ul className="col-md-4 col-lg-4 col-xl-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
src/components/Header/Header.js
ADourgarian/Syscoin-Payroll
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import logoUrl from './syscoin-logo.png'; import logoUrl2x from './logo-small@2x.png'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <Link className={s.brand} to="/"> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="255" height="52" alt="Syscoin Payroll" /> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}>Syscoin Payroll</h1> <p className={s.bannerDesc}>Syscoin transactions made easy</p> </div> </div> </div> ); } } export default withStyles(s)(Header);
src/app/views/CurriculumVitae/index.js
nhardy/web-scaffold
import React, { Component } from 'react'; import { Helmet } from 'react-helmet'; import { Link } from 'react-router'; import cx from 'classnames'; import config from 'app/config'; import { smoothScrollTo } from 'app/lib/scroll'; import { makeAbsoluteUrl, makeTitle } from 'app/lib/social'; import DefaultLayout from 'app/layouts/Default'; import P from 'app/components/P'; import profileImg from 'app/assets/images/profile.jpg'; import profileImg2x from 'app/assets/images/profile-2x.jpg'; import profileImg3x from 'app/assets/images/profile-3x.jpg'; import styles from './styles.styl'; const TITLE = 'Curriculum Vitæ'; const DESCRIPTION = [ 'The Résumé of Sydney-based student and developer, Nathan Hardy.', 'I have previously worked on a variety of web applications and services used by millions of Australians.', ].join(' '); export default class CurriculumVitae extends Component { scroll = (e) => { e.preventDefault(); smoothScrollTo(Math.min( this._resume.offsetTop - document.querySelector('#siteHeader').offsetHeight, document.body.scrollHeight - window.innerHeight, )); }; render() { return ( <DefaultLayout className={styles.root}> <Helmet> <title>{TITLE}</title> <meta property="og:title" content={makeTitle(TITLE)} /> <meta property="og:description" content={DESCRIPTION} /> <meta property="og:image" content={makeAbsoluteUrl(profileImg3x)} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content={config.twitter.handle} /> <meta name="twitter:title" content={makeTitle(TITLE)} /> <meta name="twitter:description" content={DESCRIPTION} /> <meta name="twitter:image" content={makeAbsoluteUrl(profileImg3x)} /> </Helmet> <h1 className={styles.heading}>Curriculum Vitæ</h1> <section className={styles.main}> <div className={styles.imageWrapper}> <img className={styles.profile} src={profileImg} srcSet={`${profileImg2x} 2x, ${profileImg3x} 3x`} alt="Profile" /> </div> <div className={styles.overview}> <span className={styles.greeting}>Hello,&nbsp;</span> <span className={styles.meta}>this is my Curriculum Vitæ</span> <nav className={styles.nav}> <ul className={styles.links}> <li className={styles.link}><a href="#resume" onClick={this.scroll}>Résumé</a></li> <li className={styles.link}><Link to="/projects">Projects</Link></li> <li className={styles.link}><Link to="/contact">Contact Me</Link></li> </ul> </nav> <P className={styles.paragraph}> I&apos;m a graduate of the {' '} <a href="https://www.uts.edu.au/future-students/information-technology/about-information-technology/bit-co-operative-scholarship" target="_blank" rel="noopener noreferrer" > Bachelor of Information Technology Co-operative Scholarship Program </a> {' '} at the {' '} <a href="https://www.uts.edu.au/" target="_blank" rel="noopener noreferrer">University of Technology, Sydney</a> {' '} with a passion for IT and computer science. {' '} I also studied overseas in Dunedin, New Zealand at the {' '} <a href="http://www.otago.ac.nz/" target="_blank" rel="noopener noreferrer">University of Otago</a> {' '} for my final semester. {' '} I am currently working at {' '} <a href="https://www.kablamo.com.au/" target="_blank" rel="noopener noreferrer">Kablamo</a> {' '} as a Full Stack Engineer {' '} as a Full Stack Engineer contracted to the {' '} <abbr title="Australian Broadcasting Corporation">ABC</abbr> {' '} working on ABC&apos;s Apple News pipeline. </P> <P className={styles.paragraph}> I have previously interned at {' '} <a href="https://www.appliancesonline.com.au/" target="_blank" rel="noopener noreferrer">Appliances Online</a> {' '} as a front end web developer. {' '} Prior to that, I have interned for and subsequently worked at {' '} <a href="http://www.nineentertainmentco.com.au/" target="_blank" rel="noopener noreferrer">Nine Digital</a> {' '} as a full stack developer building the {' '} <a href="https://www.9now.com.au/">9Now</a> {' '} <abbr title="Video On Demand">VOD</abbr> {' '} website and APIs. </P> <P className={styles.paragraph}> Further information is available upon request through the <Link to="/contact">contact form</Link>. </P> </div> </section> <article className={styles.resume}> <h2 id="resume" className={styles.subheading} ref={ref => (this._resume = ref)}>Résumé</h2> <section> <h3 className={styles.category}>Work History</h3> <div className={styles.workplace}> <h4 className={styles.position}>Full Stack Engineer at Kablamo</h4> <h5 className={styles.dates}>March 2018 &mdash; present</h5> <P className={cx(styles.paragraph, styles.duties)}> I am currently working full time at {' '} <a href="https://www.kablamo.com.au/" target="_blank" rel="noopener noreferrer">Kablamo</a> {' '} as a Full Stack Engineer. {' '} At the time of writing, I am contracted to the {' '} <abbr title="Australian Broadcasting Corporation">ABC</abbr> {' '} working on their Apple News pipeline. {' '} Before that, I was contracted to {' '} <a href="https://www.switch.tv/" target="_blank" rel="noopener noreferrer">Switch Media</a> {' '} working on the {' '} <a href="http://freeviewnz.tv/" target="_blank" rel="noopener noreferrer">Freeview New Zealand</a> {' '} <abbr title="Hybrid Broadband Broadcast Television">HbbTV</abbr> {' '} application. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Intern at Appliances Online</h4> <h5 className={styles.dates}>January 2017 &mdash; July 2017</h5> <P className={cx(styles.paragraph, styles.duties)}> As part of my university degree, my third year placement was at Appliances Online. {' '} At Appliances Online I mainly worked on the website frontend which made use of AngularJS. {' '} Here, I was able to refine my frontend skills and at the same time learn new frameworks and tools. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Developer at Mi9/Nine Digital</h4> <h5 className={styles.dates}>December 2015 &mdash; December 2016</h5> <P className={cx(styles.paragraph, styles.duties)}> Upon completion of my internship, I was offered to continue with Mi9 (now Nine Digital) {' '} on the 9Now project - Channel 9&apos;s AVOD catch up and streaming platform. I worked with a variety of services that power 9Now. I gathered API requirements for 9Now&apos;s API, working with internal teams. I developed portions of the APIs that power 9Now Website and Apps and worked on the 9Now website, {' '} developing features through the agile process. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Intern at Mi9</h4> <h5 className={styles.dates}>July 2015 &mdash; December 2015</h5> <P className={cx(styles.paragraph, styles.duties)}> As part of my university degree, I was required to complete two 6 month industry placements. {' '} Work at Mi9 consisted of both frontend and backend work for 9Jumpin and 9Now. {' '} Work on 9Jumpin consisted of business-as-usual tasks, {' '} as well as show experience builds for high-profile shows such as Channel 9&apos;s The Block. {' '} For a majority of my time working on 9Jumpin {' '} I was the sole developer with the site in maitenance mode while 9Now was built. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Recovery Presentation Associate at Big W Macquarie Centre</h4> <h5 className={styles.dates}>April 2015 &mdash; September 2015</h5> <P className={cx(styles.paragraph, styles.duties)}> My role in the Macquarie Centre store consisted of store recovery and presentation duties. {' '} My work here concluded when I decided to focus on balancing my academic commitments with my full-time internship at Mi9. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Recovery Presentation Associate at Big W Ballina</h4> <h5 className={styles.dates}>December 2012 &mdash; December 2014</h5> <P className={cx(styles.paragraph, styles.duties)}> My position involved a variety of tasks including nightfill, service duties, customer service, {' '} checkouts, customer championing, home entertainment and photolab work. {' '} In January of 2015 I relocated to Sydney for tertiary education, {' '} and applied for a transfer to the Macqaurie Centre store which was finalised in April 2015. </P> </div> <div className={styles.workplace}> <h4 className={styles.position}>Big W Retail Traineeship</h4> <h5 className={styles.dates}>September 2012 &mdash; December 2012</h5> <P className={cx(styles.paragraph, styles.duties)}> I participated in a work experience program with Big W whilst at school which entailed one day per week (9 to 5) for six weeks. {' '} At the conclusion of this program I was offered paid employment, which I accepted. </P> </div> </section> <section> <h3 className={styles.category}>Education</h3> <div className={styles.institution}> <h4 className={styles.course}>Study Abroad at University of Otago, Dunedin, New Zealand</h4> <h5 className={styles.dates}>July 2017 &mdash; November 2017</h5> <P className={cx(styles.paragraph, styles.outline)}> For my final semester, I studied abroad at the {' '} <a href="http://www.otago.ac.nz" target="_blank" rel="noopener noreferrer">University of Otago</a>. Here, I am studied Computer Science electives to further my technical understanding in the field. </P> </div> <div className={styles.institution}> <h4 className={styles.course}> Bachelor of Information Technology (BIT) Co-operative Scholarship Program {' '} at University of Technology, Sydney </h4> <h5 className={styles.dates}>2015 &mdash; 2017</h5> <P className={cx(styles.paragraph, styles.outline)}> I am a graduate of the Bachelor of Information Technology Co-operative Scholarship Program with the {' '} <abbr title="University of Technology, Sydney">UTS</abbr>, {' '} which involved two 6-month industry placements. </P> </div> <div className={styles.institution}> <h4 className={styles.course}>Higher School Certificate</h4> <h5 className={styles.dates}>2014</h5> <table className={styles.table}> <thead> <tr> <th>Subject</th> <th>Result</th> </tr> </thead> <tbody> <tr><td>English Standard</td><td>78</td></tr> <tr><td>Mathematics</td><td><abbr title="Exempt">*</abbr></td></tr> <tr><td>Mathematics Extension 1</td><td>84</td></tr> <tr><td>Mathematics Extension 2</td><td>78</td></tr> <tr><td>Physics</td><td>89</td></tr> <tr><td>Chemistry</td><td>86</td></tr> <tr><td>Software Design and Development</td><td>89</td></tr> </tbody> <tfoot> <tr><th>ATAR</th><th>92.90</th></tr> </tfoot> </table> </div> </section> <section> <h3 className={styles.category}>Other</h3> <div className={styles.achievement}> <h4 className={styles.challenge}>GovHackNZ</h4> <h5 className={styles.dates}>2017</h5> <P className={cx(styles.paragraph, styles.outline)}> In July 2017, whilst in Dunedin, I participated in GovHackNZ, {' '} forming a team with 3 individuals whom I met at the event. {' '} Together, we produced a visual essay website, {' '} <a href="https://github.com/nhardy/south-of-45" target="_blank" rel="noopener noreferrer">South Of 45</a> {' '} aggregating different open government data sources to derive meaningful insights for the local council. {' '} Our submission won two cash prizes totalling NZ$1500. {' '} To find out more, read the {' '} <Link to="/govhack#govhack2017">details on the GovHack page</Link>. </P> </div> <div className={styles.achievement}> <h4 className={styles.challenge}>GovHack Sydney</h4> <h5 className={styles.dates}>2016</h5> <P className={cx(styles.paragraph, styles.outline)}> In July 2016, immediately after a work hackathon, {' '} I worked over the weekend with 3 University classmates to produce a location-based social network, {' '} <a href="https://github.com/nhardy/tagger" target="_blank" rel="noopener noreferrer">Tagger</a> {' '} which made use of the Government {' '} <abbr title="Point Of Interest">POI</abbr> {' '} database for GovHack Sydney. {' '} To find out more, read the {' '} <Link to="/govhack#govhack2016">details on the GovHack page</Link>. </P> </div> <div className={styles.achievement}> <h4 className={styles.challenge}>NCSS Summer School</h4> <h5 className={styles.dates}>2014 &mdash; 2015</h5> <P className={cx(styles.paragraph, styles.outline)}> In January of 2014, I participated in the NCSS Summer School in the Python/web stream. {' '} We were tasked with building a social networking website and for this I worked as part of a team on {' '} <a href="https://github.com/nhardy/word-by-word" target="_blank" rel="noopener noreferrer">Word By Word</a>. </P> <P className={cx(styles.paragraph, styles.outline)}> In January of 2015, I participated in the embedded systems stream of the NCSS Summer School. {' '} This involved working with electronic components in circuits and manipulating these with C/C++ code on Arduino robots. </P> </div> <div className={styles.achievement}> <h4 className={styles.challenge}>NCSS Python Challenge</h4> <h5 className={styles.dates}>2012 &mdash; 2014</h5> <P className={cx(styles.paragraph, styles.outline)}> I participated in the National Computer Science School Python Challenge during high school. {' '} In 2013 and 2014, I took part in the advanced stream which involved working with binary data, {' '} steganography, breadth-first and depth-first searches, grammar parsing and a variety of other concepts. </P> </div> </section> </article> </DefaultLayout> ); } }
react/features/base/label/components/CircularLabel.web.js
bgrozev/jitsi-meet
// @flow import React from 'react'; import AbstractCircularLabel, { type Props as AbstractProps } from './AbstractCircularLabel'; type Props = AbstractProps & { /** * Additional CSS class names to add to the root of {@code CircularLabel}. */ className: string, /** * HTML ID attribute to add to the root of {@code CircularLabel}. */ id: string }; /** * React Component for showing short text in a circle. * * @extends Component */ export default class CircularLabel extends AbstractCircularLabel<Props, {}> { /** * Default values for {@code CircularLabel} component's properties. * * @static */ static defaultProps = { className: '' }; /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { className, id, label } = this.props; return ( <div className = { `circular-label ${className}` } id = { id }> { label } </div> ); } }
app/assets/javascripts/react/views/My/TokenNewPage.js
Madek/madek-webapp
import React from 'react' import f from 'lodash' import ui from '../../lib/ui.coffee' import UI from '../../ui-components/index.coffee' import RailsForm from '../../lib/forms/rails-form.cjsx' const t = ui.t class TokenNewPage extends React.Component { render(props = this.props) { const action = f.get(props, 'get.actions.create') if (!action) return false const descriptionTxt = f.get(props, 'get.given_props.description') || '' const callbackUrl = f.get(props, 'get.given_props.callback_url') const textAreaStyle = { minHeight: 'initial', resize: 'vertical' } return ( <div className="by-center" style={{ marginLeft: 'auto', marginRight: 'auto' }} > <div className="ui-container bright bordered rounded mal phm pbm" style={{ display: 'inline-block', minWidth: '420px' }} > <RailsForm name="api_token" method={action.method} action={action.url} authToken={props.authToken} > <div className="ui-form-group rowed prn pbs"> <h3 className="title-l">{t('api_tokens_create_title')}</h3> </div> {callbackUrl && ( <div className="ui-alert confirmation normal mbs"> {t('api_tokens_callback_description')} <br /> <samp className="f5 code">URL: {callbackUrl}</samp> <input type="hidden" name="callback_url" value={callbackUrl} /> </div> )} <div className="ui-form-group rowed pan "> <label className="form-label"> {t('api_tokens_create_description')} <textarea className="form-item block" style={textAreaStyle} name={'api_token[description]'} defaultValue={descriptionTxt} rows={Math.max(3, descriptionTxt.split('\n').length + 1)} /> </label> </div> <label className="ui-form-group rowed pan mbs"> <div className="form-label"> {t('api_tokens_head_permissions')} </div> <div className="form-item"> <label className="col1of2"> <input type="checkbox" defaultChecked={true} disabled /> {t('api_tokens_list_scope_read')} </label> <label className="col1of2"> <input type="checkbox" name={'api_token[scope_write]'} defaultChecked={false} /> {t('api_tokens_list_scope_write')} </label> </div> </label> <div className="ui-actions mtm"> <UI.Button type="submit" className="primary-button"> {t('api_tokens_create_submit')} </UI.Button> <UI.Button href={action.url} className="button"> {t('api_tokens_create_cancel')} </UI.Button> </div> </RailsForm> </div> </div> ) } } module.exports = TokenNewPage
src/routes/main/about/About.js
labzero/lunch
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Grid from 'react-bootstrap/lib/Grid'; import s from './About.scss'; const About = () => ( <div className={s.root}> <Grid className={s.grid}> <h2>About Lunch</h2> <p> Hi! I’m {' '} <a href="https://jeffreyatw.com" rel="noopener noreferrer" target="_blank">Jeffrey</a> , the guy behind Lunch. I created Lunch when my coworkers at {' '} <a href="https://labzero.com" rel="noopener noreferrer" target="_blank">Lab Zero</a> {' '} realized we had fallen into sort of a rut, food-wise. We kept going to the same few places, and our routine was getting stale. So I made Lunch, an easy way to keep a list of our favorite restaurants, and decide where to go! </p> <p> It’s worked great for us. Every day around 10:30 (we eat early to beat the crowds), we all hop on Lunch and vote for whatever looks good. Eventually, a consensus is reached, and we’re on our way. That, or a whole bunch of places are tied for votes, and so we just, y’know, talk it over like humans. </p> <p> Either way, I hope you have fun using Lunch! I think it’s helped us grow closer as coworkers, because we’re more invested in trying new places together, and making sure we leave the office for a little bit each day. Hot tip: set up a reminder in Slack to vote where to go every day! </p> <pre className={s.slackSnippet}>/remind #general &quot;Vote for lunch! https://lunch.pink&quot; at 10:30am every weekday</pre> <h3 id="privacy">Privacy</h3> <p> I haven’t talked to a lawyer, but I should probably reassure you about what might happen with your data when you sign up. </p> <h4>Open-source</h4> <p> First of all, Lunch is {' '} <a href="https://github.com/labzero/lunch" rel="noopener noreferrer" target="_blank"> open-source and available on GitHub </a> . If you’re ever doubtful about what we’re doing with stuff like your email address or your team’s daily decisions, you can have a look yourself. </p> <h4>Storing your data</h4> <p> Public sign-ups for Lunch are currently closed. If you try to log in with your Google account and you don’t already have a Lunch account, I’m not going to store any of your data, or keep a record that you even tried to log in &mdash; but you will be prompted to sign up for an invitation. </p> <p> For those who are already Lunch users, when you link a Google account I only store your email address, your name, and your Google profile ID. </p> <h4>Email use</h4> <p> I only plan on sending email for stuff like password resets and notifications that you’ve been added to a new team. I’m certainly not interested in using your email address for any reason other than to identify you when you log in. On Lunch, the only people who can see your email address are owners of the teams you’re a part of. </p> <h4>Cookies</h4> <p> Like pretty much any website with a login, Lunch will tell your browser to hold onto a cookie that identifies you as being logged in. There’s also a separate “session” cookie that makes sure you’re the same person from page to page, so you can see success or failure messages when doing things like requesting a password reset. </p> <h4>Google Analytics</h4> <p> This site also uses {' '} <a href="https://analytics.google.com/" rel="noopener noreferrer" target="_blank"> Google Analytics </a> {' '} to give me an idea of what sorts of people are using Lunch, and from where. {' '} <a href="https://support.google.com/analytics/answer/6004245?hl=en" rel="noopener noreferrer" target="_blank"> You can read more about their own policies </a> , which are pretty standard (they store a few cookies as well), but it’s worth pointing out that the tracking is anonymous &mdash; there’s no way they or I can tell exactly who you are. </p> <h4>Cost</h4> <p> Lunch is currently free. Unlimited users per team, and each user can create or be a part of up to three teams. I don’t plan on putting any limitations on what’s currently offered, but I might consider charging for future features, whatever those might be. Either way, I haven’t even set up a way for you to give me money, so I wouldn’t worry about it. </p> <h4>Advertising</h4> <p> That said, I’m not against advertisements, or sponsored list items, or something of the sort. If I do reach out to restaurants to advertise on Lunch, I’d display tasteful advertisements based on their proximity to your team. I wouldn’t give advertisers info like the specific names of teams, or the people on it, or anything “personally identifiable” like that. Again, this is all just potential stuff in the future, so it’s just a heads up for now. </p> <h4>Be excellent to each other</h4> <p> Oh and finally, don’t be mean to your teammates. I don’t think there’s any need for global moderation on a service this limited, but like, don’t tag restaurants as “disgusting” or delete places you don’t like. Just don’t vote for them. Otherwise, your team owner’s totally free to kick you out. </p> <p> Any other questions or things I forgot to mention? Drop me a line at {' '} <a href="mailto:jeffrey@labzero.com">jeffrey@labzero.com</a> . I’d be happy to hear from you. </p> <p> I last updated this page on May 1, 2017. </p> </Grid> </div> ); export default withStyles(s)(About);
app/components/Loading.js
zhanghaj00/shop-reactnative
/** * ShopReactNative * * @author Tony Wong * @date 2016-08-13 * @email 908601756@qq.com * @copyright Copyright © 2016 EleTeam * @license The MIT License (MIT) */ import React from 'react'; import { StyleSheet, View, Text, ActivityIndicator, } from 'react-native'; import Common from '../common/constants'; export default class Loading extends React.Component { render() { return ( <View style={styles.loading}> <ActivityIndicator color="white"/> <Text style={styles.loadingTitle}>加载中……</Text> </View> ) } } const styles = StyleSheet.create({ loading: { backgroundColor: 'gray', height: 80, width: 100, borderRadius: 10, justifyContent: 'center', alignItems: 'center', position: 'absolute', top: (Common.window.height-80)/2, left: (Common.window.width-100)/2, }, loadingTitle: { marginTop: 10, fontSize: 14, color: 'white' } })
src/components/widgets/O_SimpleForm_H_2/Dropdown/index.js
humaniq/humaniq-pwa-website
import React, { Component } from 'react'; import * as T from "prop-types"; import './styles.scss'; import {cssClassName} from 'utils' const cn = cssClassName('M_Dropdown_H') import onClickOutside from 'react-onclickoutside' import A_InputText_H from 'A_InputText_H' class M_Dropdown extends Component { state = { isOpened: false, value: this.props.value || '', inputValue: '' } handleClickOutside = () => { this.setState({isOpened:false, inputValue: this.state.value}) } handleClick = () =>{ if(!this.state.isOpened) this.setState({isOpened: true}) } handleChange = (selected) => { this.setState({inputValue: selected, isOpened:false, value: selected}) this.props.onChange(selected) } getListOptions(options, isOpened, selected) { let renderOptions if(options.length){ renderOptions = options.map(option => { return ( <ol className={cn('list-options-item', {selected: selected === option})} key={'key_' + option} onClick={() => this.handleChange(option)} >{option}</ol> ) }) }else{ renderOptions = <ol className={cn('list-options-item')} onClick={() => this.setState({inputValue: ''})} >No results</ol> } return ( <div className={cn('list-wrapper', {closed: !isOpened})}> <ul className={cn('list-options')}> {renderOptions} </ul> </div> ) } getOptions(options, filter){ return( options.filter(country => country.toLowerCase().includes(filter.toLowerCase())) ) } render() { const {options, selected, error} = this.props; const {isOpened, inputValue} = this.state; const filteredOptions = this.getOptions(options, inputValue) const listOptions = this.getListOptions(filteredOptions, isOpened, selected) return ( <div className={cn('root')} onClick={this.handleClick}> <div className={cn('select', {isOpened})}> <div className={cn('inner')}> <A_InputText_H error={error} setFocus = {isOpened} placeholder='Your country' value = {inputValue} onFocus = {() => this.setState({inputValue: ''})} handleChange={value => this.setState({inputValue: value})} /> </div> </div> {listOptions} </div> ) } } M_Dropdown.propTypes = { options: T.array.isRequired, selected: T.string.isRequired, error: T.string }; M_Dropdown.defaultProps = { } export default onClickOutside(M_Dropdown)
src/components/TextInputCSSModules/TextInputCSSModules.js
ThomasBem/ps-react-thomasbem
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; import styles from './textInput.css'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { return ( <div className={styles.fieldset}> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} className={error && styles.inputError} {...props}/> {children} {error && <div className={styles.error}>{error}</div>} </div> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
src/panels/ControlPanel/FilterPanel/index.js
Kitware/visualizer
import React from 'react'; import PropTypes from 'prop-types'; import ActionList from 'paraviewweb/src/React/Widgets/ActionListWidget'; import style from 'VisualizerStyle/ToggleIcons.mcss'; import { connect } from 'react-redux'; import { selectors, actions, dispatch } from '../../../redux'; const ICON_MAPPING = { source: style.sourceIcon, filter: style.filterIcon, }; // ---------------------------------------------------------------------------- export function FilterPanel(props) { if (!props.visible) { return null; } return ( <ActionList className={props.className} list={props.list} onClick={props.applyFilter} /> ); } FilterPanel.propTypes = { className: PropTypes.string, visible: PropTypes.bool, list: PropTypes.array, applyFilter: PropTypes.func.isRequired, }; FilterPanel.defaultProps = { className: '', visible: true, list: [], }; // Binding -------------------------------------------------------------------- /* eslint-disable arrow-body-style */ export default connect((state) => { return { list: selectors.proxies .getAvailableList(state) .map((i) => ({ name: i.name, icon: ICON_MAPPING[i.icon] })), applyFilter: (name) => { dispatch( actions.proxies.createProxy( name, selectors.proxies.getActiveSourceId(state) ) ); dispatch(actions.ui.updateVisiblePanel(0)); }, }; })(FilterPanel);
src/routes/app/routes/ui/routes/pricingTables/components/PricingTables.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; const PricingTables = () => ( <div> <div className="divider divider-lg" /> <div className="row"> <div className="col-md-3 col-xsm-6"> <section className="pricing-table pricing-table-primary"> <header><h2>Free</h2></header> <p className="pricing-price"><span className="pricing-sign">$</span>0.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>No Support</li> <li>1 Website</li> <li>10GB Disk Space</li> <li>3 Database</li> <li>1 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-primary">Buy now</a></footer> </section> </div> <div className="col-md-3 col-xsm-6"> <section className="pricing-table pricing-table-success"> <header><h2>Basic</h2></header> <p className="pricing-price"><span className="pricing-sign">$</span>29.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>24/7 Support</li> <li>1 Website</li> <li>100GB Disk Space</li> <li>10 Database</li> <li>10 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-success">Get it now</a></footer> </section> </div> <div className="col-md-3 col-xsm-6"> <section className="pricing-table pricing-table-warning"> <header> <h2>Standard</h2> </header> <p className="pricing-price"><span className="pricing-sign">$</span>39.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>24/7 Support</li> <li>Unlimited Website</li> <li>500GB Disk Space</li> <li>25 Database</li> <li>50 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-warning">Get it now</a></footer> </section> </div> <div className="col-md-3 col-xsm-6"> <section className="pricing-table pricing-table-danger"> <header> <h2>Ultimate</h2> </header> <p className="pricing-price"><span className="pricing-sign">$</span>99.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>24/7 Support</li> <li>Unlimited Website</li> <li>Unlimited Disk Space</li> <li>Unlimited Database</li> <li>100 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-danger">Get it now</a></footer> </section> </div> </div> <div className="row"> <div className="col-md-3 col-xsm-6"> <section className="pricing-table pricing-table-info"> <header><h2>Basic</h2></header> <p className="pricing-price"><span className="pricing-sign">$</span>29.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>24/7 Support</li> <li>1 Website</li> <li>100GB Disk Space</li> <li>10 Database</li> <li>10 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-info">Get it now</a></footer> </section> </div> <div className="col-md-3 col-xsm-6"> <section className="pricing-table"> <header> <h2>Standard</h2> </header> <p className="pricing-price"><span className="pricing-sign">$</span>39.00<span className="pricing-sub">/mo</span></p> <div className="pricing-plan-details"> <p className="pricing-lead">Including</p> <ul> <li>24/7 Support</li> <li>Unlimited Website</li> <li>500GB Disk Space</li> <li>25 Database</li> <li>50 Email Address</li> </ul> </div> <footer><a href="javascript:;" className="btn btn-default">Get it now</a></footer> </section> </div> </div> </div> ); const Page = () => ( <section className="container-fluid no-breadcrumbs chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><PricingTables /></div> </QueueAnim> </section> ); module.exports = Page;
client/src/app-components/popup-message.js
ivandiazwm/opensupports
import React from 'react'; import i18n from 'lib-app/i18n'; import ModalContainer from 'app-components/modal-container'; import Button from 'core-components/button'; import Icon from 'core-components/icon'; import Message from 'core-components/message'; class PopupMessage extends React.Component { static propTypes = Message.propTypes; static contextTypes = { closeModal: React.PropTypes.func }; static open(props) { ModalContainer.openModal( <PopupMessage {...props}/>, true, true ); } componentDidMount() { this.refs.closeButton && this.refs.closeButton.focus(); } render() { return ( <div className="popup-message"> <Message {...this.props} className="popup-message__message"/> <Button className="popup-message__close-button" iconName="times" type="clean" ref="closeButton" onClick={this.closeModal.bind(this)}/> </div> ); } closeModal() { if (this.context.closeModal) { this.context.closeModal(); } } } export default PopupMessage;
src/components/Header/Header.js
albperezbermejo/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../../utils/Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
src/components/PopupBlocked.js
prjctrft/mantenuto
import React from 'react'; import { ClipLoader } from 'react-spinners'; import RefitButton from 'components/RefitButton'; const PopupBlocked = (props) => ( <div> <h3>Your room will open up in a new window. Make sure you turn off your browser's popup blocker!</h3> <RefitButton onClick={() => props.openWindow()} content={'Go to Room!'} /> </div> ) export default PopupBlocked
example/src/TextField.js
ryo33/react-state-redux
import React from 'react' import { connect } from '../../src/index' const mapStateToProps = (state, componentState) => ({ value: componentState }) function componentReducer(state = "", { type, payload }) { switch (type) { case 'CHANGE': return payload default: return state } } const TextField = ({ value, dispatch, dispatchToThis }) => <div> <input value={value} onChange={(event) => dispatchToThis({type: 'CHANGE', payload: event.target.value})} /> </div> export default connect(mapStateToProps)(TextField, componentReducer)
libs/util.js
dersoncheng/react-native-iconfont-text
import React from 'react'; const glypyMapMaker = (glypy) => Object.keys(glypy).map((key) => { return { key, value: String.fromCharCode(parseInt(glypy[key], 16)) }; }).reduce((map, glypy) => { map[glypy.key] = glypy.value return map; }, {}); export { glypyMapMaker };
test/fixtures/basic/pages/stateless.js
dstreet/next.js
import React from 'react' export default () => <h1>My component!</h1>
examples/js/app.js
pvoznyuk/react-bootstrap-table
import React from 'react'; import ReactDOM from 'react-dom'; import { IndexRoute, Router, Route } from 'react-router'; import createHistory from 'history/lib/createHashHistory'; const history = createHistory( { queryKey: false } ); import App from './components/App'; import Home from './components/Home'; import GettingStarted from './components/GettingStarted'; import PageNotFound from './components/PageNotFound'; const routes = ( <Router history={ history }> <Route path='/' component={ App }> <IndexRoute component={ Home } /> <Route path='getting-started' component={ GettingStarted }/> <Route path='examples'> <Route path='basic' component={ require('./basic/demo') } /> <Route path='column' component={ require('./column/demo') } /> <Route path='sort' component={ require('./sort/demo') } /> <Route path='column-format' component={ require('./column-format/demo') } /> <Route path='column-filter' component={ require('./column-filter/demo') } /> <Route path='selection' component={ require('./selection/demo') } /> <Route path='pagination' component={ require('./pagination/demo') } /> <Route path='manipulation' component={ require('./manipulation/demo') } /> <Route path='cell-edit' component={ require('./cell-edit/demo') } /> <Route path='style' component={ require('./style/demo') } /> <Route path='advance' component={ require('./advance/demo') } /> <Route path='others' component={ require('./others/demo') } /> <Route path='complex' component={ require('./complex/demo') } /> <Route path='extra-panel' component={ require('./extra-panel/demo') } /> </Route> <Route path='*' component={ PageNotFound }/> </Route> </Router> ); ReactDOM.render(routes, document.querySelector('#root'));
index.js
EmilScherdin/react-native-local-notification
import React, { Component } from 'react'; import { PanResponder, View, Text, StyleSheet, Platform, LayoutAnimation, InteractionManager, StatusBar, UIManager } from 'react-native'; import PropTypes from 'prop-types'; import timer from 'react-native-timer'; class LocalNotificationItem extends Component { constructor(props) { super(props); this._panResponder = null; this.fullTextHeight = null; this.textHeightSetCurrentTouch = false; this.state = { topMargin: -180, isShowing: false, draggedHeight: 0, }; this.onLayout = this.onLayout.bind(this); this.hideNotification = this.hideNotification.bind(this); } componentDidMount() { timer.setTimeout(`duration-${this.props.itemId}`, this.hideNotification, this.props.duration); } isPress(y, x) { return Math.abs(y) < 4 && Math.abs(x) < 4; } hideNotification() { const config = { ...LayoutAnimation.Presets.linear, duration: 250, } LayoutAnimation.configureNext(config, () => { this.props.onNotificationHide(this.props.itemId); }); this.setState({topMargin: -200}); } componentWillMount() { this._panResponder = PanResponder.create({ onStartShouldSetPanResponderCapture: (evt, gestureState) => true, onPanResponderTerminationRequest: (evt, gestureState) => true, onStartShouldSetPanResponder: (evt, gestureState) => true, onShouldBlockNativeResponder: (evt, gestureState) => true, onMoveShouldSetPanResponder: (evt, gestureState) => true, onPanResponderTerminate: (evt, gestureState) => {}, onMoveShouldSetPanResponderCapture: (evt, gestureState) => Math.abs(gestureState.dx) > 100 || Math.abs(gestureState.dy) > 1, onPanResponderGrant: (evt, gestureState) => { this.textHeightSetCurrentTouch = false; timer.clearTimeout(`duration-${this.props.itemId}`); }, onPanResponderMove: (evt, gestureState) => { this.setState({ draggedHeight: gestureState.dy, }); }, onPanResponderRelease: (evt, gestureState) => { if (this.isPress(gestureState.dy, gestureState.dx)) { this.props.onNotificationPress(this.props.itemId); this.hideNotification(); } else { if (this.state.draggedHeight > 0) { LayoutAnimation.easeInEaseOut(); this.setState({ draggedHeight: 0, }); } if (this.state.draggedHeight < -10){ this.hideNotification(); } else if (this.state.draggedHeight < 0) { LayoutAnimation.easeInEaseOut(); this.setState({ draggedHeight: 0, }); } } }, }); } onLayout(e) { if (this.state.isShowing) return; LayoutAnimation.easeInEaseOut(); this.setState({ topMargin: 0, isShowing: true, }); } render() { const { draggedHeight } = this.state; return ( <View style={styles.wrapper}> <View {...this._panResponder.panHandlers} style={[styles.animatedView, {marginTop: -300 + (draggedHeight < 180 ? draggedHeight : 180) + this.state.topMargin}]}> <View style={[styles.innerView, this.props.notificationStyle]}> <View style={[styles.textWrapper]}> <View onLayout={this.onLayout}> {this.props.title && (<Text style={[styles.title, this.props.titleStyle]} ellipsizeMode="tail" numberOfLines={1}>{this.props.title}</Text>)} <Text style={[styles.text, this.props.textStyle]} ellipsizeMode="tail" numberOfLines={this.props.numberOfTextLines}>{this.props.text}</Text> </View> </View> <View style={[styles.handle, this.props.handleStyle]} /> </View> </View> </View> ); } } LocalNotificationItem.propTypes = { title: PropTypes.string, text: PropTypes.string.isRequired, duration: PropTypes.number.isRequired, textStyle: PropTypes.object.isRequired, titleStyle: PropTypes.object.isRequired, numberOfTextLines: PropTypes.number.isRequired, handleStyle: PropTypes.object.isRequired, notificationStyle: PropTypes.object.isRequired, onNotificationPress: PropTypes.func.isRequired, onNotificationHide: PropTypes.func.isRequired, } LocalNotificationItem.defaultProps = { title: null, text: 'Hello 👋', }; const styles = StyleSheet.create({ wrapper: { position: 'absolute', top: 0, left: -1, right: -1, backgroundColor: 'transparent' }, animatedView: { backgroundColor: 'transparent', flex: 1, }, innerView: { backgroundColor: 'white', borderColor: '#ddd', borderBottomWidth: StyleSheet.hairlineWidth, borderRightWidth: StyleSheet.hairlineWidth, borderLeftWidth: StyleSheet.hairlineWidth, paddingTop: 300, borderBottomLeftRadius: 4, borderBottomRightRadius: 4, justifyContent: 'flex-end' }, title: { height: 24, paddingTop: 6, color: 'black', fontWeight: 'bold', paddingHorizontal: 8, justifyContent: 'flex-end', fontSize: 16, }, textWrapper: { backgroundColor: 'transparent', flex: 1, overflow: 'hidden', }, text: { fontSize: 16, paddingTop: 4, paddingBottom: 4, paddingHorizontal: 8, color: '#333' }, handle: { width: 40, height: 4, borderRadius: 40, backgroundColor: 'rgba(0,0,0,.2)', marginBottom: 6, marginTop: 4, alignSelf: 'center' } }) class LocalNotification extends Component { constructor(props) { super(props); this.state = { notifications: [] }; this.hideNotification = this.hideNotification.bind(this); this.onNotificationPress = this.onNotificationPress.bind(this); } onNotificationPress(id) { const index = this.state.notifications.findIndex(item => item.id === id); const noti = this.state.notifications[index]; noti && noti.onPress && noti.onPress(noti); } hideNotification(id) { const index = this.state.notifications.findIndex(item => item.id === id); const noti = this.state.notifications[index]; noti && noti.onHide && noti.onHide(noti); const newNotifications = this.state.notifications.slice(); newNotifications.splice(index, 1); this.setState({ notifications: newNotifications, }); newNotifications.length === 0 && Platform.OS === 'ios' && StatusBar.setHidden(false, true); } showNotification(notification) { const id = Math.floor(Math.random() * 1000) + Date.now(); this.setState({ notifications: [ ...this.state.notifications, { ...notification, id }] }); Platform.OS === 'ios' && StatusBar.setHidden(true, false); } render() { const { duration, textStyle, titleStyle, handleStyle, notificationStyle, numberOfTextLines } = this.props; return ( <View style={{position: 'absolute', top: 0, left: 0, right: 0}}> {this.state.notifications.map((item, i) => ( <LocalNotificationItem key={item.id} itemId={item.id} title={item.title} text={item.text} duration={duration} textStyle={textStyle} titleStyle={titleStyle} handleStyle={handleStyle} notificationStyle={notificationStyle} onNotificationPress={this.onNotificationPress} onNotificationHide={this.hideNotification} numberOfTextLines={numberOfTextLines} /> ))} </View> ); } } LocalNotification.propTypes = { duration: PropTypes.number.isRequired, textStyle: PropTypes.object.isRequired, handleStyle: PropTypes.object.isRequired, notificationStyle: PropTypes.object.isRequired, numberOfTextLines: PropTypes.number.isRequired, } LocalNotification.defaultProps = { textStyle: {}, handleStyle: {}, notificationStyle: {}, titleStyle: {}, duration: 3500, numberOfTextLines: 2, }; export default LocalNotification;
cheesecakes/plugins/settings-manager/admin/src/components/ContentHeader/index.js
strapi/strapi-examples
/** * * ContentHeader * */ import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import styles from './styles.scss'; /* eslint-disable react/require-default-props */ function ContentHeader({ name, description }) { // eslint-disable-line react/prefer-stateless-function const title = name ? <FormattedMessage id={`settings-manager.${name}`} /> : <span />; const subTitle = description ? <FormattedMessage id={`settings-manager.${description}`} /> : <span />; return ( <div className={styles.contentHeader}> <div className={styles.title}> {title} </div> <div className={styles.subTitle}> {subTitle} </div> </div> ); } ContentHeader.propTypes = { description: PropTypes.string, name: PropTypes.string, }; export default ContentHeader;
lib/components/WeatherNow/WeatherNow.js
the-oem/weathrly
import React, { Component } from 'react'; import Moment from 'moment'; import './WeatherNow.css'; const WeatherNow = (now) => { const { cityState, currentCondition, currentTemp, icon, today, todayCondition, todayHigh, todayLow, } = now; const iconUrl = `assets/svg/${icon}.svg`; const thisDate = new Moment(today).format('dddd, MMMM Do, YYYY'); return ( <section className='weather-now'> <article className='date-location'> <h2 id='date'>{thisDate}</h2> <h2 id='location'>{cityState}</h2> </article> <article className='current-conditions'> <p id='currentTemp' className='current-temp'>{currentTemp}&#8457;</p> <img src={iconUrl} className='condition-image' alt='current condition icon'/> <p id='currentCondition'>{currentCondition}</p> </article> <article className='temps-summary'> <div className='high-low'> <p id='tempHigh'>{todayHigh}&#8457;</p> <hr className='high-low-line'></hr> <p id='tempLow'>{todayLow}&#8457;</p> </div> <p id='todayCondition'>{todayCondition}</p> </article> </section> ); }; export default WeatherNow;
fields/types/boolean/BooleanField.js
pr1ntr/keystone
import React from 'react'; import Field from '../Field'; import Checkbox from '../../components/Checkbox'; import { FormField } from 'elemental'; module.exports = Field.create({ displayName: 'BooleanField', statics: { type: 'Boolean', }, propTypes: { indent: React.PropTypes.bool, label: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, path: React.PropTypes.string.isRequired, value: React.PropTypes.bool, }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, renderFormInput () { if (!this.shouldRenderField()) return; return ( <input name={this.getInputName(this.props.path)} type="hidden" value={!!this.props.value} /> ); }, renderUI () { const { indent, value, label, path } = this.props; return ( <div data-field-name={path} data-field-type="boolean"> <FormField offsetAbsentLabel={indent}> <label style={{ height: '2.3em' }}> {this.renderFormInput()} <Checkbox checked={value} onChange={this.shouldRenderField() && this.valueChanged} readonly={!this.shouldRenderField()} /> <span style={{ marginLeft: '.75em' }}> {label} </span> </label> {this.renderNote()} </FormField> </div> ); }, });
app_learn/src/constants/constant.js
liuboshuo/react-native
/** * Created by liushuo on 17/4/19. */ import React, { Component } from 'react'; import { StyleSheet, Dimensions } from 'react-native'; export const screenWidth = Dimensions.get("window").width; export const screenHeigt = Dimensions.get("window").height; export const viewBgColor = "#e6e6e6"; export const contentViewBgColor = "#fff";
test/integration/css-fixtures/multi-global-reversed/pages/_app.js
flybayer/next.js
import React from 'react' import App from 'next/app' import '../styles/global2.css' import '../styles/global1.css' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
src/docs/patterns/PrimaryPageDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Anchor from 'grommet/components/Anchor'; import Box from 'grommet/components/Box'; import Header from 'grommet/components/Header'; import Heading from 'grommet/components/Heading'; import Label from 'grommet/components/Label'; import Paragraph from 'grommet/components/Paragraph'; import Section from 'grommet/components/Section'; import DocsTemplate from '../../components/DocsTemplate'; import { DESC as BoxDesc } from '../components/box/BoxDoc'; import { DESC as CardDesc } from '../components/card/CardDoc'; import { DESC as FooterDesc } from '../components/footer/FooterDoc'; import { DESC as HeroDesc } from '../components/hero/HeroDoc'; import { DESC as HeaderDesc } from '../components/header/HeaderDoc'; import { DESC as SectionDesc } from '../components/SectionDoc'; const COMPONENTS = [ { title: 'Box', desc: BoxDesc },{ title: 'Card', desc: CardDesc },{ title: 'Footer', desc: FooterDesc },{ title: 'Header', desc: HeaderDesc },{ title: 'Hero', desc: HeroDesc },{ title: 'Section', desc: SectionDesc } ]; export default class PrimaryPageDoc extends Component { render () { const componentsList = COMPONENTS.map(({title, desc}, index) => <Box pad={{vertical:'small'}} key={`component-${index}`}> <Anchor label={title} path={`/docs/${title.toLowerCase()}`} /> <Paragraph margin="small">{desc}</Paragraph> </Box> ); return ( <DocsTemplate title="Primary Page" exampleUrl='grommet-primary-page' githubUrl="https://github.com/grommet/grommet-primary-page"> <Section pad={{between: 'large'}}> <Paragraph size="large"> The Primary Page template is bold and impactful with a large Marquee, intro, and social feed. It is most effective as a home page or landing page and can be customized with components for any purpose that fits your needs. </Paragraph> </Section> <Section> <Box direction="row" pad={{between: 'small'}} wrap={true} responsive={false}> <Box> <Label margin="small">Desktop</Label> <Box separator="all"> <Header size="small" colorIndex="grey-5" /> <Box pad="large" separator="bottom" /> <Box colorIndex="light-2" pad={{ horizontal: 'medium', vertical: 'medium', between: 'medium' }}> <Box colorIndex="light-1" pad="large" separator="all" /> <Box direction="row" pad={{ between: 'medium' }} responsive={false}> <Box colorIndex="light-1" basis="1/3" pad="large" separator="all" /> <Box colorIndex="light-1" basis="1/3" pad="large" separator="all" /> <Box colorIndex="light-1" basis="1/3" pad="large" separator="all" /> </Box> </Box> </Box> </Box> <Box> <Label margin="small">Tablet</Label> <Box separator="all"> <Header size="small" colorIndex="grey-5" /> <Box pad="large" separator="bottom" /> <Box colorIndex="light-2" pad={{ horizontal: 'medium', vertical: 'medium', between: 'medium' }}> <Box colorIndex="light-1" pad="large" separator="all" /> <Box direction="row" pad={{ between: 'medium' }} responsive={false}> <Box colorIndex="light-1" basis="1/2" pad="large" separator="all" /> <Box colorIndex="light-1" basis="1/2" pad="large" separator="all" /> </Box> </Box> </Box> </Box> <Box> <Box> <Label margin="small">Palm</Label> <Box separator="all"> <Header size="small" colorIndex="grey-5" /> <Box pad="large" separator="bottom" /> <Box colorIndex="light-2" pad={{ horizontal: 'medium', vertical: 'medium', between: 'medium' }}> <Box colorIndex="light-1" pad="large" separator="all" /> <Box pad={{ between: 'medium' }}> <Box colorIndex="light-1" pad="large" separator="all" /> <Box colorIndex="light-1" pad="large" separator="all" /> </Box> </Box> </Box> </Box> </Box> </Box> </Section> <Section> <Heading tag="h3"> Components </Heading> {componentsList} </Section> </DocsTemplate> ); } };
src/components/TimeAndSalary/SearchScreen/Helmet.js
goodjoblife/GoodJobShare
import React from 'react'; import Helmet from 'react-helmet'; import { formatTitle, formatCanonicalPath } from 'utils/helmetHelper'; import { SITE_NAME } from '../../../constants/helmetData'; const SearchScreenHelmet = ({ keyword, page }) => { const title = `查詢${keyword}的結果 - 第${page}頁`; const description = `查詢${keyword}的薪水、加班狀況、面試心得、工作心得資料的結果`; let url = formatCanonicalPath(`/search?q=${keyword}`); if (page > 1) { url = formatCanonicalPath(`/search?q=${keyword}&p=${page}`); } return ( <Helmet> <title itemProp="name" lang="zh-TW"> {title} </title> <meta name="description" content={description} /> <meta property="og:title" content={formatTitle(title, SITE_NAME)} /> <meta property="og:description" content={description} /> <meta property="og:url" content={url} /> <link rel="canonical" href={url} /> </Helmet> ); }; export default SearchScreenHelmet;
Beatbox_app/blueprints/form/files/__root__/forms/__name__Form/__name__Form.js
whiletrace/beatbox
import React from 'react' import { reduxForm } from 'redux-form' export const fields = [] const validate = (values) => { const errors = {} return errors } type Props = { handleSubmit: Function, fields: Object, } export class <%= pascalEntityName %> extends React.Component { props: Props; defaultProps = { fields: {}, } render() { const { fields, handleSubmit } = this.props return ( <form onSubmit={handleSubmit}> </form> ) } } <%= pascalEntityName %> = reduxForm({ form: '<%= pascalEntityName %>', fields, validate })(<%= pascalEntityName %>) export default <%= pascalEntityName %>
time-on-task/app/components/RadioGroup.js
ajaymore/time-on-task
import React, { Component } from 'react'; import { View } from 'react-native'; import { CheckBox } from 'react-native-elements'; import PropTypes from 'prop-types'; export default class RadioGroup extends Component { state = { checkedId: this.props.selectedId }; _checked = checkedId => { this.setState({ checkedId }); this.props.onChange(checkedId); }; render() { return ( <View> {this.props.values.map(item => ( <CheckBox key={item.id} title={item.text} checkedIcon="ios-radio-button-on" iconType="ionicon" uncheckedIcon="ios-radio-button-off-outline" checkedColor="blue" checked={this.state.checkedId === item.id} onPress={this._checked.bind(this, item.id)} /> ))} </View> ); } } RadioGroup.propTypes = { values: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, text: PropTypes.string.isRequired }) ).isRequired, onChange: PropTypes.func.isRequired, selectedId: PropTypes.string.isRequired };
src/components/Main.js
ShangShungFoundation/tib_learn_app
import React from 'react' import { Switch, Route } from 'react-router-dom' import Home from './Home' import Sentence from './Sentence' import SpellChecker from './SpellChecker' import ExportWidget from './ExportWidget' // The Main component renders one of the three provided // Routes (provided that one matches). Both the /roster // and /schedule routes will match any pathname that starts // with /roster or /schedule. The / route will only match // when the pathname is exactly the string "/" const Main = () => ( <main> <Switch> <Route exact path='/' component={Home}/> <Route path='/spellchecker' component={SpellChecker}/> <Route path='/grammar' component={Sentence}/> <Route path='/widget' //component={ExportWidget} render={(props) => <ExportWidget {...props} />} /> </Switch> </main> ) export default Main
src/Col.js
jsbranco/react-materialize
import React from 'react'; import cx from 'classnames'; import constants from './constants'; const Col = ({ children, className, node: C = 'div', s, m, l, offset, ...other }) => { let sizes = { s, m, l }; let classes = { col: true }; constants.SIZES.forEach(size => { classes[size + sizes[size]] = sizes[size]; }); if (offset) { offset.split(' ').forEach(off => { classes['offset-' + off] = true; }); } return ( <C {...other} className={cx(classes, className)}> {children} </C> ); }; Col.propTypes = { children: React.PropTypes.node, className: React.PropTypes.string, /** * Columns for large size screens */ l: React.PropTypes.number, /** * Columns for middle size screens */ m: React.PropTypes.number, /** * The node to be used for the column * @default div */ node: React.PropTypes.node, /** * To offset, simply add s2 to the class where s signifies the screen * class-prefix (s = small, m = medium, l = large) and the number after * is the number of columns you want to offset by. */ offset: React.PropTypes.string, /** * Columns for small size screens */ s: React.PropTypes.number }; export default Col;
internals/templates/notFoundPage.js
mhtsharma9482/reactTest
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1>Page Not Found</h1> ); } }
react-components/src/library/components/stem-finder.js
concord-consortium/rigse
import React from 'react' import Component from '../helpers/component' import StemFinderResult from '../components/stem-finder-result' import sortByName from '../helpers/sort-by-name' import sortResources from '../helpers/sort-resources' import fadeIn from '../helpers/fade-in' import pluralize from '../helpers/pluralize' import waitForAutoShowingLightboxToClose from '../helpers/wait-for-auto-lightbox-to-close' import filters from '../helpers/filters' import portalObjectHelpers from '../helpers/portal-object-helpers' import AutoSuggest from './search/auto-suggest' import FeaturedCollections from './featured-collections/featured-collections' import css from './stem-finder.scss' const DISPLAY_LIMIT_INCREMENT = 6 const StemFinder = Component({ getInitialState: function () { const hideFeatured = this.props.hideFeatured || false let subjectAreaKey = this.props.subjectAreaKey let gradeLevelKey = this.props.gradeLevelKey let sortOrder = this.props.sortOrder || '' if (!subjectAreaKey && !gradeLevelKey) { // // If we are not passed props indicating filters to pre-populate // then attempt to see if this information is available in the URL. // const params = this.getFiltersFromURL() subjectAreaKey = params.subject gradeLevelKey = params['grade-level'] subjectAreaKey = this.mapSubjectArea(subjectAreaKey) } // // Scroll to stem finder if we have filters specified. // if (subjectAreaKey || gradeLevelKey) { // this.scrollToFinder() } let subjectAreasSelected = [] let subjectAreasSelectedMap = {} let i if (subjectAreaKey) { let subjectAreas = filters.subjectAreas for (i = 0; i < subjectAreas.length; i++) { let subjectArea = subjectAreas[i] if (subjectArea.key === subjectAreaKey) { subjectAreasSelected.push(subjectArea) subjectAreasSelectedMap[subjectArea.key] = subjectArea } } } let gradeLevelsSelected = [] let gradeLevelsSelectedMap = {} if (gradeLevelKey) { let gradeLevels = filters.gradeLevels for (i = 0; i < gradeLevels.length; i++) { let gradeLevel = gradeLevels[i] if (gradeLevel.key === gradeLevelKey) { gradeLevelsSelected.push(gradeLevel) gradeLevelsSelectedMap[gradeLevel.key] = gradeLevel } } } // console.log("INFO stem-finder initial subject areas: ", subjectAreasSelected); return { collections: [], displayLimit: DISPLAY_LIMIT_INCREMENT, featuredCollections: [], firstSearch: true, gradeLevelsSelected: gradeLevelsSelected, gradeLevelsSelectedMap: gradeLevelsSelectedMap, hideFeatured: hideFeatured, includeOfficial: true, includeContributed: false, includeMine: false, initPage: true, isSmallScreen: window.innerWidth <= 768, keyword: '', lastSearchResultCount: 0, noResourcesFound: false, numTotalResources: 0, opacity: 1, resources: [], searching: false, searchInput: '', searchPage: 1, sortOrder: sortOrder, subjectAreasSelected: subjectAreasSelected, subjectAreasSelectedMap: subjectAreasSelectedMap, usersAuthoredResourcesCount: 0 } }, // // If the current URL is formatted to include stem finder filters, // return the filters specified in the URL as filter-name => filter-value // pairs. // getFiltersFromURL: function () { let ret = {} let path = window.location.pathname if (!path.startsWith('/')) { path = '/' + path } let parts = path.split('/') if (parts.length >= 4 && parts[1] === 'resources') { ret[parts[2]] = parts[3] } return ret }, mapSubjectArea: function (subjectArea) { switch (subjectArea) { case 'biology': case 'life-science': return 'life-sciences' case 'engineering': return 'engineering-tech' } return subjectArea }, UNSAFE_componentWillMount: function () { waitForAutoShowingLightboxToClose(function () { this.search() }.bind(this)) }, handlePageScroll: function (event) { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop if ( scrollTop > window.innerHeight / 2 && !this.state.searching && this.state.resources.length !== 0 && !(this.state.displayLimit >= this.state.numTotalResources) ) { this.search(true) } }, handleLightboxScroll: function (event) { const scrollTop = event.srcElement.scrollTop if ( scrollTop > window.innerHeight / 3 && !this.state.searching && this.state.resources.length !== 0 && !(this.state.displayLimit >= this.state.numTotalResources) ) { this.search(true) } }, componentDidMount: function () { if (document.getElementById('pprfl')) { document.getElementById('pprfl').addEventListener('scroll', this.handleLightboxScroll) } else { document.addEventListener('scroll', this.handlePageScroll) } window.addEventListener('resize', () => { this.setState({ isSmallScreen: window.innerWidth <= 768 }) }) }, componentWillUnmount: function () { if (document.getElementById('pprfl')) { document.getElementById('pprfl').removeEventListener('scroll', this.handleLightboxScroll) } else { document.removeEventListener('scroll', this.handlePageScroll) } }, getQueryParams: function (incremental, keyword) { const searchPage = incremental ? this.state.searchPage + 1 : 1 let query = keyword !== undefined ? ['search_term=', encodeURIComponent(keyword)] : [] query = query.concat([ '&skip_lightbox_reloads=true', '&sort_order=Alphabetical', '&model_types=All', '&include_related=0', '&investigation_page=', searchPage, '&activity_page=', searchPage, '&interactive_page=', searchPage, '&collection_page=', searchPage, '&per_page=', DISPLAY_LIMIT_INCREMENT ]) // subject areas this.state.subjectAreasSelected.forEach(function (subjectArea) { subjectArea.searchAreas.forEach(function (searchArea) { query.push('&subject_areas[]=') query.push(encodeURIComponent(searchArea)) }) }) // grade this.state.gradeLevelsSelected.forEach(function (gradeFilter) { if (gradeFilter.searchGroups) { gradeFilter.searchGroups.forEach(function (searchGroup) { query.push('&grade_level_groups[]=') query.push(encodeURIComponent(searchGroup)) }) } // TODO: informal learning? }) let includedResources = this.state.includeMine ? '&include_mine=1' : '' includedResources += this.state.includeOfficial ? '&include_official=1' : '' includedResources += this.state.includeContributed ? '&include_contributed=1' : '' query.push(includedResources) return query.join('') }, search: function (incremental) { let displayLimit = incremental ? this.state.displayLimit + DISPLAY_LIMIT_INCREMENT : DISPLAY_LIMIT_INCREMENT // short circuit further incremental searches when all data has been downloaded if (incremental && (this.state.lastSearchResultCount === 0)) { this.setState({ displayLimit: displayLimit }) return } let featuredCollections = incremental ? this.state.featuredCollections.slice(0) : [] let resources = incremental ? this.state.resources.slice(0) : [] let searchPage = incremental ? this.state.searchPage + 1 : 1 let keyword = jQuery.trim(this.state.searchInput) if (keyword !== '') { ga('send', 'event', 'Home Page Search', 'Search', keyword) } this.setState({ keyword, searching: true, noResourcesFound: false, featuredCollections: featuredCollections, resources: resources }) jQuery.ajax({ url: Portal.API_V1.SEARCH, data: this.getQueryParams(incremental, keyword), dataType: 'json' }).done(function (result) { let numTotalResources = 0 const results = result.results const usersAuthoredResourcesCount = result.filters.number_authored_resources let lastSearchResultCount = 0 results.forEach(function (result) { result.materials.forEach(function (material) { portalObjectHelpers.processResource(material) resources.push(material) if (material.material_type === 'Collection') { featuredCollections.push(material) } lastSearchResultCount++ }) numTotalResources += result.pagination.total_items }) if (featuredCollections.length > 1) { featuredCollections.sort(sortByName) } resources = sortResources(resources, this.state.sortOrder) if (this.state.firstSearch) { fadeIn(this, 1000) } this.setState({ firstSearch: false, featuredCollections: featuredCollections, resources: resources, numTotalResources: numTotalResources, searchPage: searchPage, displayLimit: displayLimit, searching: false, noResourcesFound: numTotalResources === 0, lastSearchResultCount: lastSearchResultCount, usersAuthoredResourcesCount: usersAuthoredResourcesCount }) this.showResources() }.bind(this)) }, buildFilterId: function (filterKey) { const filterKeyWords = filterKey.split('-') const filterId = filterKeyWords.length > 1 ? filterKeyWords[0] + filterKeyWords[1].charAt(0).toUpperCase() + filterKeyWords[1].slice(1) : filterKeyWords[0] return filterId }, scrollToFinder: function () { if (document.getElementById('finderLightbox')) { document.getElementById('finderLightbox').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' }) } }, noOptionsSelected: function () { if ( this.state.subjectAreasSelected.length === 0 && this.state.gradeLevelsSelected.length === 0 ) { return true } else { return false } }, renderLogo: function (subjectArea) { const filterId = this.buildFilterId(subjectArea.key) const selected = this.state.subjectAreasSelectedMap[subjectArea.key] const className = selected ? css.selected : null const clicked = function () { const subjectAreasSelected = this.state.subjectAreasSelected.slice() const subjectAreasSelectedMap = this.state.subjectAreasSelectedMap const index = subjectAreasSelected.indexOf(subjectArea) if (index === -1) { subjectAreasSelectedMap[subjectArea.key] = subjectArea subjectAreasSelected.push(subjectArea) jQuery('#' + css[filterId]).addClass(css.selected) ga('send', 'event', 'Home Page Filter', 'Click', subjectArea.title) } else { subjectAreasSelectedMap[subjectArea.key] = undefined subjectAreasSelected.splice(index, 1) jQuery('#' + css[filterId]).removeClass(css.selected) } // console.log("INFO subject areas", subjectAreasSelected); this.setState({ subjectAreasSelected: subjectAreasSelected, subjectAreasSelectedMap: subjectAreasSelectedMap }, this.search) this.scrollToFinder() this.setState({ hideFeatured: true, initPage: false }) }.bind(this) return ( <li key={subjectArea.key} id={css[filterId]} className={className} onClick={clicked}> {subjectArea.title} </li> ) }, renderGLLogo: function (gradeLevel) { let className = 'portal-pages-finder-form-filters-logo' const filterId = this.buildFilterId(gradeLevel.key) var selected = this.state.gradeLevelsSelectedMap[gradeLevel.key] if (selected) { className += ' ' + css.selected } const clicked = function () { const gradeLevelsSelected = this.state.gradeLevelsSelected.slice() const gradeLevelsSelectedMap = this.state.gradeLevelsSelectedMap const index = gradeLevelsSelected.indexOf(gradeLevel) if (index === -1) { gradeLevelsSelectedMap[gradeLevel.key] = gradeLevel gradeLevelsSelected.push(gradeLevel) jQuery('#' + css[filterId]).addClass(css.selected) ga('send', 'event', 'Home Page Filter', 'Click', gradeLevel.title) } else { gradeLevelsSelectedMap[gradeLevel.key] = undefined gradeLevelsSelected.splice(index, 1) jQuery('#' + css[filterId]).removeClass(css.selected) } // console.log("INFO subject areas", subjectAreasSelected); this.setState({ gradeLevelsSelected: gradeLevelsSelected, gradeLevelsSelectedMap: gradeLevelsSelectedMap }, this.search) this.scrollToFinder() this.setState({ hideFeatured: true, initPage: false }) }.bind(this) return ( <li key={gradeLevel.key} id={css[filterId]} className={className} onClick={clicked}> {gradeLevel.title} </li> ) }, renderSubjectAreas: function () { const containerClassName = this.state.isSmallScreen ? css.finderOptionsContainer : `${css.finderOptionsContainer} ${css.open}` return ( <div className={containerClassName}> <h2 onClick={this.handleFilterHeaderClick}>Subject</h2> <ul> {filters.subjectAreas.map(function (subjectArea) { return this.renderLogo(subjectArea) }.bind(this))} </ul> </div> ) }, renderGradeLevels: function () { const containerClassName = this.state.isSmallScreen ? css.finderOptionsContainer : `${css.finderOptionsContainer} ${css.open}` return ( <div className={containerClassName}> <h2 onClick={this.handleFilterHeaderClick}>Grade Level</h2> <ul> {filters.gradeFilters.map(function (gradeLevel) { return this.renderGLLogo(gradeLevel) }.bind(this))} </ul> </div> ) }, handleOfficialClick: function (e) { e.currentTarget.classList.toggle(css.selected) this.setState({ hideFeatured: true, includeOfficial: !this.state.includeOfficial }, this.search) ga('send', 'event', 'Home Page Filter', 'Click', 'Official') }, handleCommunityClick: function (e) { e.currentTarget.classList.toggle(css.selected) this.setState({ hideFeatured: true, includeContributed: !this.state.includeContributed }, this.search) ga('send', 'event', 'Home Page Filter', 'Click', 'Community') }, clearFilters: function () { jQuery('.portal-pages-finder-form-subject-areas-logo').removeClass(css.selected) this.setState({ subjectAreasSelected: [], gradeLevelsSelected: [], keyword: '', searchInput: '' }, this.search) }, clearKeyword: function () { this.setState({ keyword: '', searchInput: '' }, () => this.search()) }, toggleFilter: function (type, filter) { this.setState({ initPage: false }) const selectedKey = type + 'Selected' const selectedFilters = this.state[selectedKey].slice() const index = selectedFilters.indexOf(filter) if (index === -1) { selectedFilters.push(filter) jQuery('#' + filter.key).addClass(css.selected) ga('send', 'event', 'Home Page Filter', 'Click', filter.title) } else { selectedFilters.splice(index, 1) jQuery('#' + filter.key).removeClass(css.selected) } let state = {} state[selectedKey] = selectedFilters this.setState(state, this.search) }, handleSearchInputChange: function (searchInput) { this.setState({ searchInput }) }, handleSearchSubmit (e) { e.preventDefault() e.stopPropagation() this.search() this.scrollToFinder() this.setState({ hideFeatured: true, initPage: false }) }, handleAutoSuggestSubmit (searchInput) { this.setState({ hideFeatured: true, initPage: false }) this.setState({ searchInput }, () => { this.search() this.scrollToFinder() }) }, handleSortSelection (e) { e.preventDefault() e.stopPropagation() this.setState({ hideFeatured: true, initPage: false }) this.setState({ sortOrder: e.target.value }, () => { this.search() }) ga('send', 'event', 'Finder Sort', 'Selection', e.target.value) }, renderSearch: function () { const containerClassName = this.state.isSmallScreen ? css.finderOptionsContainer : `${css.finderOptionsContainer} ${css.open}` return ( <div className={containerClassName}> <h2 onClick={this.handleFilterHeaderClick}>Keywords</h2> <form onSubmit={this.handleSearchSubmit}> <div className={'portal-pages-search-input-container'}> <AutoSuggest name={'search-terms'} query={this.state.searchInput} getQueryParams={this.getQueryParams} onChange={this.handleSearchInputChange} onSubmit={this.handleAutoSuggestSubmit} placeholder={'Type search term here'} skipAutoSearch /> </div> </form> </div> ) }, isAdvancedUser: function () { const isAdvancedUser = Portal.currentUser.isAdmin || Portal.currentUser.isAuthor || Portal.currentUser.isManager || Portal.currentUser.isResearcher return (isAdvancedUser) }, renderAdvanced: function () { return ( <> <div className={css.finderOptionsContainer}> <h2 onClick={this.handleFilterHeaderClick}>Advanced</h2> <ul> <li id={css.official} className={css.selected} onClick={(e) => this.handleOfficialClick(e)}>Official</li> <li id={css.community} onClick={(e) => this.handleCommunityClick(e)}>Community</li> </ul> </div> <div className={css.advancedSearchLink}> <a href='/search' title='Advanced Search'>Advanced Search</a> </div> </> ) }, renderForm: function () { const isAdvancedUser = this.isAdvancedUser() return ( <div className={'col-3 ' + css.finderForm}> <div className={'portal-pages-finder-form-inner'} style={{ opacity: this.state.opacity }}> {this.renderSearch()} {this.renderSubjectAreas()} {this.renderGradeLevels()} {isAdvancedUser && this.renderAdvanced()} </div> </div> ) }, handleFilterHeaderClick: function (e) { e.currentTarget.parentElement.classList.toggle(css.open) }, handleShowOnlyMine: function (e) { this.setState({ includeMine: !this.state.includeMine }, this.search) }, renderShowOnly: function () { const { includeMine } = this.state return ( <div className={css.showOnly}> <label htmlFor='includeMine'><input type='checkbox' name='includeMine' value='true' id='includeMine' onChange={this.handleShowOnlyMine} defaultChecked={includeMine} /> Show only resources I authored</label> </div> ) }, renderSortMenu: function () { const sortValues = ['Alphabetical', 'Less time required', 'More time required', 'Newest', 'Oldest'] return ( <div className={css.sortMenu}> <label htmlFor='sort'>Sort by</label> <select name='sort' value={this.state.sortOrder} onChange={this.handleSortSelection}> {sortValues.map(function (sortValue, index) { return <option key={`${sortValue}-${index}`} value={sortValue}>{sortValue}</option> })} </select> </div> ) }, renderResultsHeader: function () { const { displayLimit, noResourcesFound, numTotalResources, searching, usersAuthoredResourcesCount } = this.state const finderHeaderClass = this.isAdvancedUser() || usersAuthoredResourcesCount > 0 ? `${css.finderHeader} ${css.advanced}` : css.finderHeader if (noResourcesFound || searching) { return ( <div className={finderHeaderClass}> <h2>Activities List</h2> {(this.isAdvancedUser() || usersAuthoredResourcesCount > 0) && this.renderShowOnly()} <div className={css.finderHeaderResourceCount}> {noResourcesFound ? 'No Resources Found' : 'Loading...'} </div> {this.renderSortMenu()} </div> ) } const showingAll = displayLimit >= numTotalResources const multipleResources = numTotalResources > 1 const resourceCount = showingAll ? numTotalResources : displayLimit + ' of ' + numTotalResources jQuery('#portal-pages-finder').removeClass('loading') return ( <div className={finderHeaderClass}> <h2>Activities List</h2> {(this.isAdvancedUser() || usersAuthoredResourcesCount > 0) && this.renderShowOnly()} <div className={css.finderHeaderResourceCount}> {showingAll && multipleResources ? 'Showing All ' : 'Showing '} <strong> {resourceCount + ' ' + pluralize(resourceCount, 'Activity', 'Activities')} </strong> </div> {this.renderSortMenu()} </div> ) }, renderLoadMore: function () { if ((this.state.resources.length === 0) || (this.state.displayLimit >= this.state.numTotalResources)) { return null } }, showResources: function () { setTimeout(function () { const resourceItems = document.querySelectorAll('.resourceItem') resourceItems.forEach(function (resourceItem) { resourceItem.style.opacity = 1 }) }, 500) }, renderResults: function () { if (this.state.firstSearch) { return ( <div className={css.loading}> Loading </div> ) } let featuredCollections = this.state.featuredCollections featuredCollections = featuredCollections.sort(() => Math.random() - Math.random()).slice(0, 3) const resources = this.state.resources.slice(0, this.state.displayLimit) return ( <> {(!this.state.hideFeatured && this.state.initPage && this.noOptionsSelected() && featuredCollections.length > 0) && <FeaturedCollections featuredCollections={featuredCollections} /> } {this.renderResultsHeader()} <div className={css.finderResultsContainer}> {resources.map((resource, index) => { return <StemFinderResult key={`${resource.external_url}-${index}`} resource={resource} index={index} showResources={this.showResources} /> })} </div> {this.state.searching ? <div className={css.loading}>Loading</div> : null} {this.renderLoadMore()} </> ) }, render: function () { // console.log("INFO stem-finder render()"); return ( <div className={'cols ' + css.finderWrapper}> {this.renderForm()} <div id={css.finderResults} className='portal-pages-finder-results col-9' style={{ opacity: this.state.opacity }}> {this.renderResults()} </div> </div> ) } }) export default StemFinder
ui/src/js/findTree/FindTreePage.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import React, { Component } from 'react'; import Notification from '../common/components/Notification'; import FindTrees from './FindTrees'; import TreeItem from './TreeItem'; import TreesFound from './TreesFound'; require('./findTreePage.less'); export default class FindTreePage extends Component { constructor(props) { super(props); this.state = { treesFound: false, certificateId: '', trees: [], certificate: {} }; } findCertificate(certificateId) { var that = this; this.setState({ certificateId: certificateId }); axios .get('http://localhost:8081/certificate/search/' + encodeURIComponent(certificateId)) .then(function(response) { var result = response.data; that.setState({ trees: result }); axios.get('http://localhost:8081/certificate/summary/' + encodeURIComponent(certificateId)).then(function(response) { var result = response.data; that.setState({ certificate: result, treesFound: true }); }); }) .catch(function(response) { that.refs.notification.addNotification(counterpart.translate('CERTIFICATE.NOT_EXISTS'), counterpart.translate('CERTIFICATE.NOT_EXISTS_TEXT'), 'error'); }); } render() { var content; if (this.state.treesFound) { content = ( <TreesFound certificateId={this.state.certificateId} certificate={this.state.certificate}> {this.state.trees.map(function(tree, i) { let imageUrl = 'http://localhost:8081/treeType/image/' + tree.treeType.imageFile + '/60/60'; return <TreeItem imageUrl={imageUrl} content={tree} key={i} />; })} </TreesFound> ); } else { content = <FindTrees findCertificate={this.findCertificate.bind(this)} />; } return ( <div className="container paddingTopBottom15"> <div className="row findTree">{content}</div> <Notification ref="notification" /> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
src/index.js
dchudz/PlannedPooling
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
lib/components/Row.js
Raathigesh/Dazzle
import React from 'react'; import PropTypes from 'prop-types'; import Column from './Column'; import Widgets from './Widgets'; /** * Returns a set of columns that belongs to a row. */ function Row(props) { const { rowClass, columns, widgets, onRemove, layout, rowIndex, editable, frameComponent, editableColumnClass, droppableColumnClass, addWidgetComponentText, addWidgetComponent, onAdd, onMove, onEdit, } = props; const items = columns.map((column, index) => { // eslint-disable-line arrow-body-style return ( <Column key={index} className={column.className} onAdd={onAdd} layout={layout} rowIndex={rowIndex} columnIndex={index} editable={editable} onMove={onMove} editableColumnClass={editableColumnClass} droppableColumnClass={droppableColumnClass} addWidgetComponent={addWidgetComponent} addWidgetComponentText={addWidgetComponentText} > <Widgets key={index} widgets={column.widgets} containerClassName={column.containerClassName} widgetTypes={widgets} onRemove={onRemove} layout={layout} rowIndex={rowIndex} columnIndex={index} editable={editable} frameComponent={frameComponent} onMove={onMove} onEdit={onEdit} /> </Column> ); }); return ( <div className={rowClass}> {items} </div> ); } Row.propTypes = { /** * CSS class that should be used to represent a row. */ rowClass: PropTypes.string, /** * Columns of the layout. */ columns: PropTypes.array, /** * Widgets that should be used in the dashboard. */ widgets: PropTypes.object, /** * Layout of the dashboard. */ layout: PropTypes.object, /** * Index of the row where this column is in. */ rowIndex: PropTypes.number, /** * Indicates weather the dashboard is in editable mode or not. */ editable: PropTypes.bool, /** * Custom frame that should be used with the widget. */ frameComponent: PropTypes.func, /** * Class to be used for columns in editable mode. */ editableColumnClass: PropTypes.string, /** * CSS class to be used for columns when a widget is droppable. */ droppableColumnClass: PropTypes.string, /** * Custom AddWidget component. */ addWidgetComponent: PropTypes.func, /** * Text that should be displyed in the AddWidget component. */ addWidgetComponentText: PropTypes.string, /** * Method that should be called when a component is added. */ onAdd: PropTypes.func, /** * Method that should be called when a component is removed. */ onRemove: PropTypes.func, /** * Method that should be called when a widget is moved. */ onMove: PropTypes.func, onEdit: PropTypes.func, }; Row.defaultProps = { /** * Most CSS grid systems uses 'row' as the class name. Or not ? */ rowClass: 'row', }; export default Row;
dva/wd/src/components/CocktailCard.js
imuntil/React
import React from 'react'; import { Icon } from 'antd-mobile' import styles from './CocktailCard.css'; function CocktailCard({ more, width = '45%', data = {} }) { return ( <div className={styles.normal} style={{ width }}> <img src={data.src || require('../assets/ig-dir/cocktail-1.jpg')} alt="" /> <p className="en">{data.en || 'negroni'}</p> <p className="cn">{data.cn || '内格罗尼'}</p> { more ? <a href="javascript:;">查看更多 <Icon type="right" /></a> : null } </div> ); } export default CocktailCard;
app/addons/fauxton/navigation/components/NavBar.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Footer from './Footer'; import Burger from './Burger'; import NavLink from './NavLink'; import Brand from './Brand'; import LogoutButton from './LogoutButton'; import LoginButton from './LoginButton'; class NavBar extends Component { constructor(props) { super(props); } createLinks (links) { const { activeLink, isMinimized } = this.props; return links.map((link, i) => { return <NavLink key={i} link={link} active={activeLink} isMinimized={isMinimized} />; }); } render () { const { isMinimized, version, isLoginSectionVisible, isLoginVisibleInsteadOfLogout, activeLink, username, isNavBarVisible, toggleNavbarMenu } = this.props; if (!isNavBarVisible) { return null; } const navLinks = this.createLinks(this.props.navLinks); const bottomNavLinks = this.createLinks(this.props.bottomNavLinks); const footerNavLinks = this.createLinks(this.props.footerNavLinks); const navClasses = classNames( 'faux-navbar', {'faux-navbar--wide': !isMinimized}, {'faux-navbar--narrow': isMinimized} ); const loginSection = isLoginVisibleInsteadOfLogout ? <LoginButton active={activeLink} isMinimized={isMinimized} /> : <LogoutButton username={username} isMinimized={isMinimized} />; return ( <div className={navClasses}> <nav> <div className="faux-navbar__linkcontainer"> <Burger isMinimized={isMinimized} toggleMenu={toggleNavbarMenu}/> <div className="faux-navbar__links"> {navLinks} {bottomNavLinks} </div> <div className="faux-navbar__footer"> <Brand isMinimized={isMinimized} /> <div> {footerNavLinks} </div> <Footer version={version}/> {isLoginSectionVisible ? loginSection : null} </div> </div> </nav> </div> ); } } NavBar.propTypes = { activeLink: PropTypes.string, isMinimized: PropTypes.bool.isRequired, version: PropTypes.string, username: PropTypes.string, navLinks: PropTypes.array, bottomNavLinks: PropTypes.array, footerNavLinks: PropTypes.array, isNavBarVisible: PropTypes.bool, isLoginSectionVisible: PropTypes.bool.isRequired, isLoginVisibleInsteadOfLogout: PropTypes.bool.isRequired, toggleNavbarMenu: PropTypes.func.isRequired }; export default NavBar;
app/components/PreschoolProject/NoPermission.js
klpdotorg/tada-frontend
import React from 'react'; import PropTypes from 'prop-types'; const NoPermissionView = ({ project }) => { return ( <div> <div className="alert alert-danger"> <i className="fa fa-lock fa-lg" aria-hidden="true" /> Insufficient Privileges. Only administrators can modify boundary details. </div> <h4 className="text-primary">Project</h4> <div className="border-base" /> <div className="base-spacing-mid" /> <div>{project.name}</div> </div> ); }; NoPermissionView.propTypes = { project: PropTypes.object, }; export { NoPermissionView };
app/js/components/search/SearchInputComponent.js
theappbusiness/tab-hq
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import AppStore from '../../stores/AppStore'; import AppActionCreators from '../../actions/AppActionCreators'; import Reflux from 'reflux'; require('../../../styles/SearchComponent.sass'); function getStateFromStores() { return { searchQuery: AppStore.query }; } const SearchComponent = React.createClass({ mixins: [Reflux.listenTo(AppStore, '_onChange')], getInitialState: getStateFromStores, handleChange(e) { let value = e.target.value; AppActionCreators.search(value); }, _onChange() { this.setState(getStateFromStores()); }, componentDidMount() { if (this.props.focusOnLoad) { ReactDOM.findDOMNode(this.refs.searchInput).focus(); ReactDOM.findDOMNode(this.refs.searchInput).setSelectionRange(AppStore.getSearchQuery().length, 1); } }, render() { return ( <div className='search-component'> <i className='fa fa-search'></i> <input value={this.state.searchQuery} onChange={this.handleChange} ref='searchInput' placeholder='Search...' /> </div> ); } }); module.exports = SearchComponent;
examples/05 Customize/Handles and Previews/index.js
globexdesigns/react-dnd
import React, { Component } from 'react'; import Container from './Container'; export default class CustomizeHandlesAndPreviews extends Component { render() { return ( <div> <p> <b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/05%20Customize/Handles%20and%20Previews'>Browse the Source</a></b> </p> <p> React DnD lets you choose the draggable node, as well as the drag preview node in your component's <code>render</code> function. You may also use an <a href='https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image'><code>Image</code></a> instance that you created programmatically once it has loaded. </p> <Container /> </div> ); } }
docs/src/app/components/pages/components/DropDownMenu/ExampleLongMenu.js
pancho111203/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; const items = []; for (let i = 0; i < 100; i++ ) { items.push(<MenuItem value={i} key={i} primaryText={`Item ${i}`} />); } export default class DropDownMenuLongMenuExample extends React.Component { constructor(props) { super(props); this.state = {value: 10}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu maxHeight={300} value={this.state.value} onChange={this.handleChange}> {items} </DropDownMenu> ); } }