path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/Events/EventsList.js
llukasxx/school-organizer-front
import React from 'react' import ReactPaginate from 'react-paginate' import EventListItem from './EventListItem' export class EventsList extends React.Component { constructor(props) { super(props) this.renderEventListItems = this.renderEventListItems.bind(this) this.handlePageClick = this.handlePageClick.bind(this) this.renderPagination = this.renderPagination.bind(this) this.state = {currentPage: 0} } renderEventListItems() { const { events } = this.props let eventsList = [] const sortFunction = function(a,b) { if(Date.parse(a.date) < Date.parse(b.date)) return -1 if(Date.parse(a.date) > Date.parse(b.date)) return 1 return 0 } events.sort(sortFunction).map((event) => { eventsList.push(<EventListItem event={event} key={event.id}/>) }) return eventsList } handlePageClick(data) { this.setState({currentPage: data.selected}) this.props.getEvents(data.selected + 1) } renderPagination() { return ( <li className="list-group-item"> <ReactPaginate previousLabel={"<"} pageNum={this.props.count/5} nextLabel={">"} breakLabel={<a>...</a>} breakClassName={"break-me"} clickCallback={this.handlePageClick} marginPagesDisplayed={1} pageRangeDisplayed={2} containerClassName={"pagination"} subContainerClassName={"pages pagination"} activeClassName={"active"} initialSelected={0} forceSelected={this.state.currentPage}/> </li> ) } componentWillReceiveProps(nextProps) { if(nextProps.activeFilter != this.props.activeFilter) { this.setState({currentPage: 0}) } } render () { return ( <ul className="list-group"> {this.renderEventListItems()} {this.renderPagination()} </ul> ) } } export default EventsList
src/components/AdminDocSecuence.js
aurigadl/EnvReactAsk
import React from 'react' import Reflux from 'reflux'; import * as cSecAc from '../actions/confSecu'; import confSecuStore from '../stores/confSecu'; import { Form, InputNumber, Radio, Input, Button } from 'antd'; const FormItem = Form.Item; const ButtonGroup = Button.Group; const AdminDocSecuence = Form.create()(React.createClass({ mixins: [Reflux.connect(confSecuStore, 'cSecSt')], getInitialState: function () { return { valOld:'', typedata: 'string' } }, handleSwitch: function (e){ cSecAc.setConfSecuence(''); cSecAc.setConfType(e.target.value); this.setState({ valOld: ''}); }, handleValue: function (e) { var reg = ''; var value = e.target.value; const type = this.state.cSecSt.type; if(type === 'string'){ reg = /^[a-zA-Z]+$/; }else{ reg = /^[0-9]+$/; } if (reg.test(value) || value === '' ) { cSecAc.setConfSecuence(value); this.setState({ valOld: value }); }else{ cSecAc.setConfSecuence(this.state.valOld); } }, handleSubmitForm: function (e) { e.preventDefault(); const { cSecSt } = this.state; cSecAc.saveConfSecuence(); }, render: function () { const { getFieldDecorator} = this.props.form; const {typedata, cSecSt} = this.state; var resError = ''; if(cSecSt.secuence.length < 5 ){ resError = 'error'; } const formItemLayout = { labelCol: { sm: { span: 6 }, }, wrapperCol: { sm: { span: 18 }, }, }; return ( <Form onSubmit={this.handleSubmitForm}> <h4> Secuencia General: </h4> <p> Agrega una secuencia a los documentos generados y lleva un conteo unico de las documentación. </p> <FormItem {...formItemLayout} label="Consecutivo" style={{ 'marginTop': 15 }} > <Radio.Group onChange={this.handleSwitch} defaultValue={typedata} value={cSecSt.type}> <Radio.Button value="number">Numeros</Radio.Button> <Radio.Button value="string">Letras</Radio.Button> </Radio.Group> </FormItem> <FormItem {...formItemLayout} validateStatus={resError} help="Un valor mayor o igual a cinco caracteres" label='Valor Actual o Inicial' > <Input value={cSecSt.secuence} onChange={this.handleValue}/> </FormItem> <ButtonGroup> <Button onClick={cSecAc.fetchConfSecuence}> Restaurar </Button> <Button disabled={resError? true: false} type="primary" htmlType="submit">Grabar</Button> </ButtonGroup> </Form> ); } })); export default AdminDocSecuence
src/pwa.js
delwiv/saphir
import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './helpers/Html'; export default function () { return `<!doctype html>${ReactDOM.renderToStaticMarkup(<Html />)}`; }
app/javascript/mastodon/features/explore/results.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { expandSearch } from 'mastodon/actions/search'; import Account from 'mastodon/containers/account_container'; import Status from 'mastodon/containers/status_container'; import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag'; import { List as ImmutableList } from 'immutable'; import LoadMore from 'mastodon/components/load_more'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = state => ({ isLoading: state.getIn(['search', 'isLoading']), results: state.getIn(['search', 'results']), }); const appendLoadMore = (id, list, onLoadMore) => { if (list.size >= 5) { return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />); } else { return list; } }; const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts', ImmutableList()).map(item => ( <Account key={`account-${item}`} id={item} /> )), onLoadMore); const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags', ImmutableList()).map(item => ( <Hashtag key={`tag-${item.get('name')}`} hashtag={item} /> )), onLoadMore); const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses', ImmutableList()).map(item => ( <Status key={`status-${item}`} id={item} /> )), onLoadMore); export default @connect(mapStateToProps) class Results extends React.PureComponent { static propTypes = { results: ImmutablePropTypes.map, isLoading: PropTypes.bool, multiColumn: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; state = { type: 'all', }; handleSelectAll = () => this.setState({ type: 'all' }); handleSelectAccounts = () => this.setState({ type: 'accounts' }); handleSelectHashtags = () => this.setState({ type: 'hashtags' }); handleSelectStatuses = () => this.setState({ type: 'statuses' }); handleLoadMoreAccounts = () => this.loadMore('accounts'); handleLoadMoreStatuses = () => this.loadMore('statuses'); handleLoadMoreHashtags = () => this.loadMore('hashtags'); loadMore (type) { const { dispatch } = this.props; dispatch(expandSearch(type)); } render () { const { isLoading, results } = this.props; const { type } = this.state; let filteredResults = ImmutableList(); if (!isLoading) { switch(type) { case 'all': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses)); break; case 'accounts': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts)); break; case 'hashtags': filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags)); break; case 'statuses': filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses)); break; } if (filteredResults.size === 0) { filteredResults = ( <div className='empty-column-indicator'> <FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' /> </div> ); } } return ( <React.Fragment> <div className='account__section-headline'> <button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button> <button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button> <button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button> <button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Posts' /></button> </div> <div className='explore__search-results'> {isLoading ? <LoadingIndicator /> : filteredResults} </div> </React.Fragment> ); } }
packages/mineral-ui-icons/src/IconGroupWork.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconGroupWork(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5a2.5 2.5 0 0 1 0-5 2.5 2.5 0 0 1 0 5zM9.5 8a2.5 2.5 0 0 1 5 0 2.5 2.5 0 0 1-5 0zm6.5 9.5a2.5 2.5 0 0 1 0-5 2.5 2.5 0 0 1 0 5z"/> </g> </Icon> ); } IconGroupWork.displayName = 'IconGroupWork'; IconGroupWork.category = 'action';
src/containers/Root.js
dpca/whats-free
// @flow import React from 'react'; import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom'; import App from './App'; import type { Store } from '../types'; type Props = { store: Store, }; function Root({ store }: Props) { return ( <BrowserRouter> <Provider store={store}> <App /> </Provider> </BrowserRouter> ); } export default Root;
lib/index.js
t-obi/react-simple-resize
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Handle from './Handle'; class Resize extends Component { static propTypes = { initialHeight: PropTypes.number, initialWidth: PropTypes.number, minHeight: PropTypes.number, minWidth: PropTypes.number, children: PropTypes.node, style: PropTypes.object, className: PropTypes.string, handleStyle: PropTypes.object, handleClassName: PropTypes.string, handleColor: PropTypes.string, }; static defaultProps = { initialHeight: 300, initialWidth: 300, minHeight: 100, minWidth: 100, }; state = { height: this.props.initialHeight, width: this.props.initialWidth, }; handleChange = (width, height) => { this.setState({ width: Math.max(width, this.props.minWidth), height: Math.max(height, this.props.minHeight), }); }; render() { const { width, height } = this.state; const style = { margin: 50, position: 'relative', ...this.props.style, width, height, }; return ( <div style={style} className={this.props.className} > {this.props.children} <Handle onChange={this.handleChange} width={width} height={height} style={this.props.handleStyle} className={this.props.handleClassName} handleColor={this.props.handleColor} /> </div> ); } } export default Resize;
components/Header.js
spirityy/dashboard
import React from 'react' import { Link } from 'react-router' export default class Header extends React.Component { render() { return( <header> <div className="logo"> <Link to="/">Logo</Link> </div> <div className="hd"> Dashboard </div> </header> ) } }
client/components/Skeleton.js
VoiSmart/Rocket.Chat
import { Box, Skeleton } from '@rocket.chat/fuselage'; import React from 'react'; export const FormSkeleton = (props) => ( <Box w='full' pb='x24' {...props}> <Skeleton mbe='x8' /> <Skeleton mbe='x4' /> <Skeleton mbe='x4' /> <Skeleton mbe='x8' /> <Skeleton mbe='x4' /> <Skeleton mbe='x8' /> </Box> );
tests/react_modules/es6class-types-callsite.js
fletcherw/flow
/* @flow */ import React from 'react'; import Hello from './es6class-types-module'; type Props = {name: string}; class HelloLocal extends React.Component<void, Props, void> { props: Props; render(): React.Element<*> { return <div>{this.props.name}</div>; } } class Callsite extends React.Component<void, Props, void> { render(): React.Element<*> { return ( <div> <Hello /> <HelloLocal /> </div> ); } } module.exports = Callsite;
components/Pages/Home/Home.js
pigflymoon/geo-app
import React from 'react'; import Page from "../Page"; import Banner from '../../Banner' import NewsSlider from '../../NewsSlider' import QuakesListMap from '../../QuakesListMap' export default class Home extends React.Component { render() { return ( <Page> <Banner /> <NewsSlider type="news" /> <div className="container"> <QuakesListMap type="Quakes" /> </div> </Page> ); } }
openex-front/src/components/Error.js
Luatix/OpenEx
import React from 'react'; import * as R from 'ramda'; import * as PropTypes from 'prop-types'; import { withRouter } from 'react-router-dom'; import Alert from '@mui/material/Alert'; import AlertTitle from '@mui/material/AlertTitle'; class ErrorBoundaryComponent extends React.Component { constructor(props) { super(props); this.state = { error: null, stack: null }; } componentDidCatch(error, stack) { this.setState({ error, stack }); } render() { if (this.state.stack) { return this.props.display; } return this.props.children; } } ErrorBoundaryComponent.propTypes = { display: PropTypes.object, children: PropTypes.node, }; export const ErrorBoundary = R.compose(withRouter)(ErrorBoundaryComponent); const SimpleError = () => ( <Alert severity="error"> <AlertTitle>Error</AlertTitle> An unknown error occurred. Please contact your administrator or the OpenEx maintainers. </Alert> ); export const errorWrapper = (Component) => { return (routeProps) => ( <ErrorBoundary display={<SimpleError />}> <Component {...routeProps} /> </ErrorBoundary> ); };
news/NewsApp.js
HKuz/FreeCodeCamp
import React from 'react'; import { Grid } from 'react-bootstrap'; import Helmet from 'react-helmet'; import { SlimWidthRow } from '../common/app/helperComponents'; import Nav from './components/Nav'; import { routes } from './routes'; const propTypes = {}; /* eslint-disable max-len */ const styles = ` .app-layout p, .app-layout li, .app-layout a, .app-layout span { font-size: 21.5px; } .app-layout hr { background-image: linear-gradient(to right, rgba(0, 100, 0, 0), rgba(0, 100, 0, 0.75), rgba(0, 100, 0, 0)); } .app-layout p { paddin-top: 8px; } .app-layout h1, .app-layout h2, .app-layout h3, .app-layout h4, .app-layout h5, .app-layout h6 { padding-top: 35px; padding-bottom: 0px; } .app-layout h1 { font-size: 42px; } .app-layout h2 { font-size: 34px; } .app-layout h3 { font-size: 32px; } `; /* eslint-enable max-len */ function NewsApp() { return ( <div> <Helmet> <style>{styles}</style> </Helmet> <Nav /> <Grid fluid={true}> <SlimWidthRow className='app-layout'>{routes}</SlimWidthRow> </Grid> </div> ); } NewsApp.displayName = 'NewsApp'; NewsApp.propTypes = propTypes; export default NewsApp;
src/components/SmallProfile/SmallProfile.js
ihnat/tream
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './SmallProfile.scss'; import Link from '../Link'; import Navigation from '../Navigation'; class SmallProfile extends Component { render() { return ( <div className={s.smallProfile}> <div className={s.smallProfile__navigation}> <a href="/">Good</a> <a href="/">Bad</a> </div> <div className={s.smallProfile__block}> <div className={s.smallProfile__pic}> <img src={require('./logo-small.png')} width="38" height="38" alt="React" /> </div> <div className={s.smallProfile__info}> <h3 className={s.smallProfile__title}>Max Troicki</h3> <p className={s.smallProfile__role}>Front-end</p> </div> </div> </div> ); } } export default withStyles(SmallProfile, s);
app/javascript/mastodon/features/account/components/account_note.js
primenumber/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Textarea from 'react-textarea-autosize'; import { is } from 'immutable'; const messages = defineMessages({ placeholder: { id: 'account_note.placeholder', defaultMessage: 'Click to add a note' }, }); class InlineAlert extends React.PureComponent { static propTypes = { show: PropTypes.bool, }; state = { mountMessage: false, }; static TRANSITION_DELAY = 200; componentWillReceiveProps (nextProps) { if (!this.props.show && nextProps.show) { this.setState({ mountMessage: true }); } else if (this.props.show && !nextProps.show) { setTimeout(() => this.setState({ mountMessage: false }), InlineAlert.TRANSITION_DELAY); } } render () { const { show } = this.props; const { mountMessage } = this.state; return ( <span aria-live='polite' role='status' className='inline-alert' style={{ opacity: show ? 1 : 0 }}> {mountMessage && <FormattedMessage id='generic.saved' defaultMessage='Saved' />} </span> ); } } export default @injectIntl class AccountNote extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, value: PropTypes.string, onSave: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { value: null, saving: false, saved: false, }; componentWillMount () { this._reset(); } componentWillReceiveProps (nextProps) { const accountWillChange = !is(this.props.account, nextProps.account); const newState = {}; if (accountWillChange && this._isDirty()) { this._save(false); } if (accountWillChange || nextProps.value === this.state.value) { newState.saving = false; } if (this.props.value !== nextProps.value) { newState.value = nextProps.value; } this.setState(newState); } componentWillUnmount () { if (this._isDirty()) { this._save(false); } } setTextareaRef = c => { this.textarea = c; } handleChange = e => { this.setState({ value: e.target.value, saving: false }); }; handleKeyDown = e => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { e.preventDefault(); this._save(); if (this.textarea) { this.textarea.blur(); } } else if (e.keyCode === 27) { e.preventDefault(); this._reset(() => { if (this.textarea) { this.textarea.blur(); } }); } } handleBlur = () => { if (this._isDirty()) { this._save(); } } _save (showMessage = true) { this.setState({ saving: true }, () => this.props.onSave(this.state.value)); if (showMessage) { this.setState({ saved: true }, () => setTimeout(() => this.setState({ saved: false }), 2000)); } } _reset (callback) { this.setState({ value: this.props.value }, callback); } _isDirty () { return !this.state.saving && this.props.value !== null && this.state.value !== null && this.state.value !== this.props.value; } render () { const { account, intl } = this.props; const { value, saved } = this.state; if (!account) { return null; } return ( <div className='account__header__account-note'> <label htmlFor={`account-note-${account.get('id')}`}> <FormattedMessage id='account.account_note_header' defaultMessage='Note' /> <InlineAlert show={saved} /> </label> <Textarea id={`account-note-${account.get('id')}`} className='account__header__account-note__content' disabled={this.props.value === null || value === null} placeholder={intl.formatMessage(messages.placeholder)} value={value || ''} onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleBlur} ref={this.setTextareaRef} /> </div> ); } }
old_boilerplate/js/components/pages/ReadmePage.react.js
hbaughman/audible-temptations
/* * ReadmePage * * This is the page users see when they click the "Setup" button on the HomePage */ import React, { Component } from 'react'; import { Link } from 'react-router'; export default class ReadmePage extends Component { render() { return ( <div> <h2>Further Setup</h2> <p>Assuming you have already cloned the repo and ran all the commands from the README (otherwise you would not be here), these are the further steps:</p> <ol> <li>Replace my name and the package name in the package.json file</li> <li>Replace the two components with your first component</li> <li>Replace the default actions with your first action</li> <li>Delete css/components/_home.css and add the styling for your component</li> <li>And finally, update the unit tests</li> </ol> <Link className="btn" to="/">Home</Link> </div> ); } }
admin/client/App/screens/Item/components/FormHeading.js
webteckie/keystone
import React from 'react'; import evalDependsOn from '../../../../../../fields/utils/evalDependsOn'; module.exports = React.createClass({ displayName: 'FormHeading', propTypes: { options: React.PropTypes.object, }, render () { if (!evalDependsOn(this.props.options.dependsOn, this.props.options.values)) { return null; } return <h3 className="form-heading">{this.props.content}</h3>; }, });
client/components/BubbleSlider.js
kauffecup/news-insights
//------------------------------------------------------------------------------ // Copyright IBM Corp. 2016 // // 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 React from 'react'; import Actions from '../Actions'; export default ({ numBubbles }) => <div className="bubble-selector"> <div className="num-bubble-label">{numBubbles + (numBubbles === 1 ? " Circle" : " Circles")}</div> <input className="slider" type="range" min="1" max="250" value={numBubbles} steps="250" onChange={e => Actions.changeNumBubbles(e.target.value)} /> <div className="help-text">(might need to adjust for screen size or if animations are laggy)</div> </div>
newclient/scripts/components/responsive-component/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import React from 'react'; export class ResponsiveComponent extends React.Component { constructor() { super(); this.windowSize = window.size; } render() { if (window.size === 'SMALL') { return this.renderMobile(); } return this.renderDesktop(); } }
js/components/projectEdit/tabDescription.js
bsusta/HelpdeskAppTemplate
import React, { Component } from 'react'; import {Alert} from 'react-native'; import {Form, Input, Label, Button, Icon, Item, Footer, FooterTab, Thumbnail, Container, Content, Card, CardItem, Text, ListItem, List, Left, Body, Right } from 'native-base'; import styles from './styles'; import {updateProject,deleteProject} from './projectEdit.gquery'; import { Actions } from 'react-native-router-flux'; import { withApollo} from 'react-apollo'; import I18n from '../../translations/'; class TabDescription extends Component { constructor(props){ super(props); this.state={ title:this.props.project.title?this.props.project.title:'', description:this.props.project.description?this.props.project.description:'' } } deleteProject(){ Alert.alert( I18n.t('settingsDeleteProjectTitle'), I18n.t('settingsDeleteProjectMessage'), [ {text: I18n.t('cancel'), style: 'cancel'}, {text: I18n.t('ok'), onPress: () =>{ this.props.client.mutate({ mutation: deleteProject, variables: { id:this.props.project.id}, }); Actions.pop(); }}, ], { cancelable: false } ); } submit(){ this.props.client.mutate({ mutation: updateProject, variables: { id:this.props.project.id,title:this.state.title,description:this.state.description}, }); Actions.pop(); } render() { // eslint-disable-line return ( <Container> <Content padder style={{ marginTop: 0 }}> <Form> <Item stackedLabel> <Label>{I18n.t('title')}</Label> <Input placeholder={I18n.t('title')} value={this.state.title} onChangeText={(value)=>this.setState({title:value})} /> </Item> <Item stackedLabel> <Label>{I18n.t('description')}</Label> <Input style={{height:100}} multiline={true} placeholder={I18n.t('description')} value={this.state.description} onChangeText={(value)=>this.setState({description:value})} /> </Item> </Form> </Content> <Footer> <FooterTab> <Button iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }} onPress={Actions.pop} > <Icon active style={{ color: 'white' }} name="md-add" /> <Text style={{ color: 'white' }} >{I18n.t('cancel')}</Text> </Button> </FooterTab> <FooterTab> <Button iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }} onPress={this.deleteProject.bind(this)}> <Icon active name="trash" style={{ color: 'white' }} /> <Text style={{ color: 'white' }} >{I18n.t('delete')}</Text> </Button> </FooterTab> <FooterTab> <Button iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }} onPress={this.submit.bind(this)}> <Icon active name="md-add" style={{ color: 'white' }} /> <Text style={{ color: 'white' }} >{I18n.t('save')}</Text> </Button> </FooterTab> </Footer> </Container> ); } } export default withApollo(TabDescription);
internals/templates/containers/HomePage/index.js
Ratholien/JobReact
/* * HomePage * * This is the first thing users see of our App, at the '/' 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 necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
node_modules/react-bootstrap/es/Breadcrumb.js
rblin081/drafting-client
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import BreadcrumbItem from './BreadcrumbItem'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var Breadcrumb = function (_React$Component) { _inherits(Breadcrumb, _React$Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Breadcrumb.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('ol', _extends({}, elementProps, { role: 'navigation', 'aria-label': 'breadcrumbs', className: classNames(className, classes) })); }; return Breadcrumb; }(React.Component); Breadcrumb.Item = BreadcrumbItem; export default bsClass('breadcrumb', Breadcrumb);
src/svg-icons/device/bluetooth-disabled.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothDisabled = (props) => ( <SvgIcon {...props}> <path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/> </SvgIcon> ); DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled); DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled'; DeviceBluetoothDisabled.muiName = 'SvgIcon'; export default DeviceBluetoothDisabled;
src/main.js
nrandecker/poller
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import createStore from './store/createStore'; import AppContainer from './containers/AppContainer'; injectTapEventPlugin(); // ======================================================== // Store Instantiation // ======================================================== const initialState = window.___INITIAL_STATE__; const store = createStore(initialState); // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root'); let render = () => { const routes = require('./routes/index').default(store); ReactDOM.render( <AppContainer store={store} routes={routes} />, MOUNT_NODE, ); }; // This code is excluded from production bundle if (__DEV__) { if (module.hot) { // Development render functions const renderApp = render; const renderError = (error) => { const RedBox = require('redbox-react').default; ReactDOM.render(<RedBox error={error} />, MOUNT_NODE); }; // Wrap render in try/catch render = () => { try { renderApp(); } catch (error) { console.error(error); renderError(error); } }; // Setup hot module replacement module.hot.accept('./routes/index', () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE); render(); }), ); } } // ======================================================== // Go! // ======================================================== render();
src/parser/demonhunter/havoc/CONFIG.js
fyruna/WoWAnalyzer
import React from 'react'; import { Mamtooth, Yajinni } from 'CONTRIBUTORS'; import SPECS from 'game/SPECS'; import retryingPromise from 'common/retryingPromise'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [Mamtooth, Yajinni], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.1.5', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Welcome to the Havoc Demon Hunter analyzer! We hope you find these suggestions and statistics useful.<br /> <br />More resources for Havoc:<br /> <a href="https://discord.gg/zGGkNGC" target="_blank" rel="noopener noreferrer">Demon Hunter Class Discord</a> <br /> <a href="https://www.wowhead.com/havoc-demon-hunter-guide" target="_blank" rel="noopener noreferrer">Wowhead Guide</a> <br /> <a href="https://www.icy-veins.com/wow/havoc-demon-hunter-pve-dps-guide" target="_blank" rel="noopener noreferrer">Icy Veins Guide</a> <br /> </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/5-Tarke', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.HAVOC_DEMON_HUNTER, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "HavocDemonHunter" */).then(exports => exports.default)), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
src/components/Category/MemberIdea.js
partneran/partneran
import React from 'react'; const MemberIdea = () => { return ( <div className="container"> <div className="section text-center"> <h2>Ideas which User Follow</h2> <div className="row"> <div className="col-md-4 text-left"> <div className="card thumbnail"> <img src="https://images.pexels.com/photos/205316/pexels-photo-205316.png?dl&fit=crop&w=640&h=426" alt="..." className="img-responsive"/> <div className="caption"> <h3>Idea Title</h3> <p> <i className="fa fa-icon fa-user"></i> Ken Duigraha &nbsp; <i className="fa fa-icon fa-tag"></i> Social Network &nbsp; <i className="fa fa-icon fa-calendar"></i> Dec 12th, 2016 </p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> <ul className="pager"> <li className="next"><a href="#">See Details <span aria-hidden="true">&rarr;</span></a></li> </ul> </div> </div> </div> <div className="col-md-4 text-left"> <div className="card thumbnail"> <img src="https://images.pexels.com/photos/39284/macbook-apple-imac-computer-39284.jpeg?dl&fit=crop&w=640&h=425" alt="..." className="img-responsive"/> <div className="caption"> <h3>Idea Title</h3> <p> <i className="fa fa-icon fa-user"></i> Ken Duigraha &nbsp; <i className="fa fa-icon fa-tag"></i> Social Network &nbsp; <i className="fa fa-icon fa-calendar"></i> Dec 12th, 2016 </p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> <ul className="pager"> <li className="next"><a href="#">See Details <span aria-hidden="true">&rarr;</span></a></li> </ul> </div> </div> </div> <div className="col-md-4 text-left"> <div className="card thumbnail"> <img src="https://images.pexels.com/photos/39284/macbook-apple-imac-computer-39284.jpeg?dl&fit=crop&w=640&h=425" alt="..." className="img-responsive"/> <div className="caption"> <h3>Idea Title</h3> <p> <i className="fa fa-icon fa-user"></i> Ken Duigraha &nbsp; <i className="fa fa-icon fa-tag"></i> Social Network &nbsp; <i className="fa fa-icon fa-calendar"></i> Dec 12th, 2016 </p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> <ul className="pager"> <li className="next"><a href="#">See Details <span aria-hidden="true">&rarr;</span></a></li> </ul> </div> </div> </div> </div> <ul className="pager"> <li className="next"><a href="#">Explore more <span aria-hidden="true">&rarr;</span></a></li> </ul> </div> </div> ) } export default MemberIdea
app/javascript/mastodon/components/column_back_button_slim.js
KnzkDev/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import ColumnBackButton from './column_back_button'; import Icon from 'mastodon/components/icon'; export default class ColumnBackButtonSlim extends ColumnBackButton { render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
src/main/resources/ui/components/Main.js
mesos/chronos
import React from 'react' import JobSummaryView from './JobSummaryView' import JobEditor from './JobEditor' import {observer} from 'mobx-react' @observer export default class Main extends React.Component { derp(event) { console.log(event) } render() { const jobSummaryStore = this.props.jobSummaryStore return ( <div className="container"> <div className="panel panel-default"> <div className="panel-heading"> <JobEditor jobSummaryStore={jobSummaryStore} /> </div> <div className="panel-body"> <div className="row"> <div className="col-md-1 bg-success">SUCCESS</div> <div className="col-md-1 bg-success">{jobSummaryStore.successCount}</div> <div className="col-md-1 bg-danger">FAILURE</div> <div className="col-md-1 bg-danger">{jobSummaryStore.failureCount}</div> <div className="col-md-1 bg-info">FRESH</div> <div className="col-md-1 bg-info">{jobSummaryStore.freshCount}</div> <div className="col-md-1 bg-primary">RUNNING</div> <div className="col-md-1 bg-primary">{jobSummaryStore.runningCount}</div> <div className="col-md-1 bg-info">QUEUED</div> <div className="col-md-1 bg-info">{jobSummaryStore.queuedCount}</div> <div className="col-md-1 bg-success">IDLE</div> <div className="col-md-1 bg-success">{jobSummaryStore.idleCount}</div> </div> </div> <JobSummaryView jobs={this.getVisibleJobs()} /> </div> </div> ) } getVisibleJobs() { return this.props.jobSummaryStore.jobSummarys } } Main.propTypes = { jobSummaryStore: React.PropTypes.object.isRequired, }
actor-apps/app-web/src/app/index.js
boyley/actor-platform
import crosstab from 'crosstab'; import React from 'react'; import Router from 'react-router'; import Raven from 'utils/Raven'; // eslint-disable-line import injectTapEventPlugin from 'react-tap-event-plugin'; import Deactivated from 'components/Deactivated.react'; import Login from 'components/Login.react'; import Main from 'components/Main.react'; import JoinGroup from 'components/JoinGroup.react'; import LoginStore from 'stores/LoginStore'; import LoginActionCreators from 'actions/LoginActionCreators'; //import AppCache from 'utils/AppCache'; // eslint-disable-line import Pace from 'pace'; Pace.start({ ajax: false, restartOnRequestAfter: false, restartOnPushState: false }); const DefaultRoute = Router.DefaultRoute; const Route = Router.Route; const RouteHandler = Router.RouteHandler; const ActorInitEvent = 'concurrentActorInit'; if (crosstab.supported) { crosstab.on(ActorInitEvent, (msg) => { if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') { window.location.assign('#/deactivated'); window.location.reload(); } }); } const initReact = () => { if (window.location.hash !== '#/deactivated') { if (crosstab.supported) { crosstab.broadcast(ActorInitEvent, {}); } if (location.pathname === '/app/index.html') { window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']); } else { window.messenger = new window.actor.ActorApp(); } } const App = React.createClass({ render() { return <RouteHandler/>; } }); const routes = ( <Route handler={App} name="app" path="/"> <Route handler={Main} name="main" path="/"/> <Route handler={JoinGroup} name="join" path="/join/:token"/> <Route handler={Login} name="login" path="/auth"/> <Route handler={Deactivated} name="deactivated" path="/deactivated"/> <DefaultRoute handler={Main}/> </Route> ); const router = Router.run(routes, Router.HashLocation, function (Handler) { injectTapEventPlugin(); React.render(<Handler/>, document.getElementById('actor-web-app')); }); if (window.location.hash !== '#/deactivated') { if (LoginStore.isLoggedIn()) { LoginActionCreators.setLoggedIn(router, {redirect: false}); } } }; window.jsAppLoaded = () => { setTimeout(initReact, 0); };
web/src/views/Main/Authenticated/PeerReview/PeerReview.js
envman/e-net
import React from 'react' import {Table, TableBody, TableRow, TableRowColumn} from 'material-ui/Table'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import {List, ListItem} from 'material-ui/List'; export class PeerReview extends React.Component { constructor(props, context) { super(props, context) this.state = { response: [] } } componentDidMount() { fetch('http://localhost:8080/reviews/groups') .then(res => res.json()) .then(response => { this.setState({ response }) }) } send = (id) => { let group = this.state.response.filter(g => g.id === id)[0] let messages = [] for (let fromPerson of group.members) { let message = fromPerson.name + ' Please Review\n' for (let toPerson of group.members) { if (toPerson.id !== fromPerson.id) { message += toPerson.name + '\n' message += 'http://localhost:3000/review/' + fromPerson.id + '/' + toPerson.id + '\n' } } message += 'Thanks!' messages.push({ message: message, to: fromPerson.email }) } let proms = messages.map(m => { return fetch('http://localhost:8080/email/send', { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({ email: m.to, text: m.message }) }) }) Promise.all(proms) .then(r => { console.log('all done') }) } reviewFeedback = (id) => { this.context.router.push("/auth/reviewfeedback/" + id) } render() { return ( <div className="container make-it-black"> <Table> <TableBody displayRowCheckbox={false}> {this.state.response.map((r, i) => ( <TableRow key={i} style={{borderBottom:'none'}}> <TableRowColumn style={{backgroundColor: 'white'}}> <Card style={{boxShadow: 'none'}}> { i % 2 === 0 ? <CardHeader title={r.name} actAsExpander={true} style={{backgroundColor: 'rgba(127, 221, 233, 0.4)'}}/> :<CardHeader title={r.name} actAsExpander={true}/> } <CardText expandable={true} style={{backgroundColor: '#FAFAFA'}}> <List> {r.members.map((e, i) => <ListItem onClick={() => this.reviewFeedback(e.id)} primaryText={e.name + ' - ' + e.email} key={i}/>)} <CardActions> <button className="btn btn-primary" onClick={() => this.send(r.id)}>Start Review Process</button> </CardActions> </List> </CardText> </Card> </TableRowColumn> </TableRow> ))} </TableBody> </Table> <div className="col-xs-1 col-xs-offset-11"> </div> </div> ) } } PeerReview.contextTypes = { router: React.PropTypes.object } export default PeerReview
client/component/schema/filter/types/string.js
johngodley/search-regex
/** * External dependencies */ import React from 'react'; import { translate as __ } from 'i18n-calypso'; /** * Internal dependencies */ import Logic from '../logic'; import { DropdownText } from 'wp-plugin-components'; import SearchFlags from 'component/search-flags'; function FilterString( props ) { const { disabled, item, onChange, schema, fetchData } = props; const { logic = 'equals', value = '', flags = [ 'case' ] } = item; const remote = schema.options === 'api' && flags.indexOf( 'regex' ) === -1 ? fetchData : false; return ( <> <Logic type="string" value={ logic } disabled={ disabled } onChange={ ( value ) => onChange( { logic: value, flags: [ 'case' ] } ) } /> { flags.indexOf( 'multi' ) === -1 ? ( <DropdownText value={ value } disabled={ disabled } onChange={ ( newValue ) => onChange( { value: newValue } ) } fetchData={ remote } /> ) : ( <textarea value={ value } disabled={ disabled } onChange={ ( ev ) => onChange( { value: ev.target.value } ) } /> ) } <SearchFlags flags={ flags } disabled={ disabled } onChange={ ( value ) => onChange( { flags: value } ) } allowRegex={ logic === 'equals' || logic === 'notcontains' } allowMultiline={ schema.multiline || false } /> </> ); } export default FilterString;
src/app1/app1.js
joeldenning/simple-single-spa-webpack-example
import React from 'react'; import ReactDOM from 'react-dom'; import singleSpaReact from 'single-spa-react'; import Root from './root.component.tsx'; const reactLifecycles = singleSpaReact({ React, ReactDOM, rootComponent: Root, domElementGetter, }); export function bootstrap(props) { return reactLifecycles.bootstrap(props); } export function mount(props) { return reactLifecycles.mount(props); } export function unmount(props) { return reactLifecycles.unmount(props); } function domElementGetter() { // Make sure there is a div for us to render into let el = document.getElementById('app1'); if (!el) { el = document.createElement('div'); el.id = 'app1'; document.body.appendChild(el); } return el; }
src/components/Feedback/Feedback.js
toddsmart/react-starter
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { 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/containers/DevTools.js
llukasxx/school-organizer-front
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> )
frontend/src/components/print/print-react/renderingDependencies.js
ecamp/ecamp3
import React from 'react' import wrap from './minimalHalJsonVuex.js' import createI18n from './i18n.js' import documents from './documents/index.js' import { pdf } from '@react-pdf/renderer' export default { React, wrap, createI18n, pdf, documents }
node_modules/react-router/es/Link.js
aalpgiray/react-hot-boilerplate-ts
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; import { ContextSubscriber } from './ContextUtils'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object, func]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; var router = this.context.router; !router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); router.push(resolveToLocation(this.props.to, router)); }, render: function render() { var _props = this.props; var to = _props.to; var activeClassName = _props.activeClassName; var activeStyle = _props.activeStyle; var onlyActiveOnIndex = _props.onlyActiveOnIndex; var props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); // Ignore if rendered outside the context of router to simplify unit testing. var router = this.context.router; if (router) { var toLocation = resolveToLocation(to, router); props.href = router.createHref(toLocation); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
src/frontend/screens/Login/index.js
Koleso/invoicer
import React from 'react'; import LoginLayout from 'screens/LoginLayout'; import SignupContainer from 'containers/SignupContainer'; const Login = () => ( <LoginLayout page="login"> <div> <h1 className="introTitle">Vítejte!</h1> <p>Taky je už slyšíte cinkat?</p> <SignupContainer action="login" /> </div> </LoginLayout> ); export default Login;
app/containers/HomePage/index.js
andyfrith/weather.goodapplemedia.com
/* * HomePage * * This is the first thing users see of our App, at the '/' route */ import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { makeSelectLoading, makeSelectError, makeSelectCurrentWeather, makeSelectForecasts } from 'containers/App/selectors'; import ForecastsList from 'components/ForecastsList'; import CurrentWeather from 'components/CurrentWeather'; import Button from 'components/Button'; import { FormattedMessage } from 'react-intl'; import { getNow } from 'utils/DateUtils'; import Form from './Form'; import Input from './Input'; import Section from './Section'; import messages from './messages'; import { loadCurrentWeather, loadForecasts } from '../App/actions'; import { changeCity } from './actions'; import { makeSelectCity } from './selectors'; import Img from './Img'; import SearchIcon from './search-glass.svg'; import Wrapper from './Wrapper'; export class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function /** * when initial state username is not null, submit the form to load repos */ componentDidMount() { if (this.props.city && this.props.city.trim().length > 0) { this.props.onSubmitForm(); } } render() { const { loading, error, currentWeather, forecasts } = this.props; const forecastsListProps = { loading, error, forecasts, }; const currentWeatherProps = { loading, error, currentWeather, }; return ( <Wrapper> <div className="header"> <div className="now">Now { getNow() }</div> <Form onSubmit={this.props.onSubmitForm}> <label style={{ fontStyle: 'italic' }} htmlFor="city"> <FormattedMessage className="searchPrompt" {...messages.searchPrompt} /> <Input id="city" type="text" placeholder="Denver" value={this.props.city} onChange={this.props.onChangeCity} /> <Img src={SearchIcon} alt="Search Icon" /> <div className="buttonHolder"> <Button onClick={this.props.onSubmitForm}>Submit</Button> </div> </label> </Form> </div> <article> <Helmet title="Home Page" meta={[ { name: 'description', content: 'A weather forecast demo application using React.js Boilerplate application' }, ]} /> <div> <Section> <CurrentWeather {...currentWeatherProps} /> <ForecastsList {...forecastsListProps} /> </Section> </div> </article> </Wrapper> ); } } HomePage.propTypes = { loading: React.PropTypes.bool, error: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), currentWeather: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), forecasts: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), onSubmitForm: React.PropTypes.func, city: React.PropTypes.string, onChangeCity: React.PropTypes.func, }; export function mapDispatchToProps(dispatch) { return { onChangeCity: (evt) => dispatch(changeCity(evt.target.value)), onSubmitForm: (evt) => { if (evt !== undefined && evt.preventDefault) { evt.preventDefault(); dispatch(loadCurrentWeather()); dispatch(loadForecasts()); } }, }; } const mapStateToProps = createStructuredSelector({ forecasts: makeSelectForecasts(), currentWeather: makeSelectCurrentWeather(), city: makeSelectCity(), loading: makeSelectLoading(), error: makeSelectError(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
src/TweetContainer.js
chelsea-le/nastywoman
// Tweets component import React from 'react'; import firebase from 'firebase'; import Tweet from './Tweet'; import TweetBox from './TweetBox'; import SortFilter from './SortFilter'; import './css/App.css' var tweetRef; var TweetContainer = React.createClass({ getInitialState:function() { return {tweets:[], order:'date'} }, componentWillMount() { tweetRef = firebase.database().ref('tweets'); }, componentDidMount:function(){ tweetRef.on('value', (snapshot)=> { // In case there are no tweets if(snapshot.val()){ this.setState({tweets:snapshot.val()}); } }); }, // Function to create a neew tweet createTweet:function(event) { event.preventDefault(); // Get form info let tweet = { author:this.props.user, text:event.target.elements['message'].value, likes:0, liked: [], time:firebase.database.ServerValue.TIMESTAMP, // FirebaseInit service comments: {} }; if (tweet.text.trim().length === 0) { alert("You must type something!"); } else { tweetRef.push(tweet); event.target.reset(); } }, // Function to like a tweet likeTweet:function(tweetId, change) { let ref = tweetRef.child(tweetId); ref.once('value').then(function(snapshot) { var newLikes = parseInt(snapshot.val().likes, 10); newLikes += change; // Update on Firebase ref.update({ likes: newLikes }); }); }, //Function that adds comments addComment:function(tweetId, text) { let ref = tweetRef.child(tweetId).child("comments"); //currenly a string that says "comment"...need to grab comment from FirebaseInit let comment = { author:this.props.user, text:text, time:firebase.database.ServerValue.TIMESTAMP // FirebaseInit service }; ref.push({comment}) }, setOrder:function(e) { this.setState({order:e.target.id}) }, render:function() { // Sort keys by likes //tweets sorted by more newest to oldest let tweetKeys = Object.keys(this.state.tweets).sort((a,b) => { var first = this.state.tweets[a] var second = this.state.tweets[b] if(this.state.order === 'date') { return second.time - first.time } else if (this.state.order === 'likes') { return second.likes - first.likes } else { var tweet1 = 0 var tweet2 = 0 if (first.comments != null) { tweet1 = Object.keys(first.comments).length } if (second.comments != null) { tweet2 = Object.keys(second.comments).length } return tweet2 - tweet1 } }); return( <div> <h4 className="messageBoardTitle">Message Board</h4> <section className="tweet-container"> <TweetBox handleSubmit={this.createTweet}/> <SortFilter clickEvent={this.setOrder}/> {/* <TweetBox handleSubmit={this.createTweet} revealComments={this.addComent}/> */} {tweetKeys.map((d) => { return <Tweet key={d} data={this.state.tweets[d]} like={() => this.likeTweet(d, 1)} dislike={() => this.likeTweet(d, -1)} revealComments={(e) => this.addComment(d, e)} /> })} </section> </div> ) } }); export default TweetContainer;
client2/src/components/whiteboard/whiteboard.js
gdomorski/CodeOut
import React, { Component } from 'react'; import axios from 'axios'; import CanvasDraw from './canvasdraw'; import Gallery from './gallery'; import WhiteboardNav from './whiteboard_nav'; import Webcams from './../webcams/webcam-bar'; import PickColor from './colorbox'; import PickBackground from './bgcolorbox'; import auth from "./../auth/auth-helper"; import Login from "./../auth/login"; export default class Whiteboard extends Component { constructor(props) { super(props); this.state = { brushColor: '#ffaff5', loggedIn: auth.loggedIn(), lineWidth: 4, canvasStyle: { backgroundColor: '#FFFFFF' }, all: false, clear: false, restore: false, tool: "pen", data: [], }; this.saveAnImage = this.saveAnImage.bind(this); this.chooseBG = this.chooseBG.bind(this); this.increaseSize = this.increaseSize.bind(this); this.decreaseSize = this.decreaseSize.bind(this); this.destroy = this.destroy.bind(this); this.bringBack = this.bringBack.bind(this); } componentDidMount(){ this.updateData(); } updateData(){ this.setState({ clear: false, }) axios.get('api/allZeeBoards') .then(function(response){ this.setState({data: response.data}); }.bind(this)) .catch(function (response) { console.log("error getting data", response); }); } increaseSize() { if (this.state.lineWidth<15){ this.setState({ clear: false, lineWidth: this.state.lineWidth += 1 }); } } decreaseSize(){ if(this.state.lineWidth>1){ this.setState({ clear: false, lineWidth: this.state.lineWidth -= 1 }) } } chooseBG(color) { let newstate = this.state; newstate.canvasStyle.backgroundColor = color.target.value; this.setState({ newstate }); } destroy() { const newCanvas = document.getElementById("canvas"), context = newCanvas.getContext("2d"), savedImage = new Image(), width = newCanvas.width, height = newCanvas.height; context.clearRect(0, 0, width, height); } bringBack() { const newCanvas = document.getElementById("canvas"), context = newCanvas.getContext("2d"), savedImage = new Image(), width = newCanvas.width, height = newCanvas.height; axios.get('api/lastBoard') .then(function (response) { console.log("response data ",response); savedImage.src = response.data; if(response.data){ context.clearRect(0, 0, width, height); context.drawImage(savedImage,0,0); } }) .catch(function (response) { console.log("error restoring image"); console.log(response); }); } saveAnImage () { let that = this, newCanvas = document.getElementById("canvas"), savedImage = new Image(); savedImage.src = newCanvas.toDataURL('image/png') axios.post('/api/boards', { thing: savedImage.src, name: 'saved' }) .then(function (response) { that.updateData(); }) .catch(function (response) { console.log("ERROR saving"); console.log(response); }); } render() { const indent = { 'marginTop': '10px' } const painting = { borderWidth: '500px', height: '500px', left: '500px' } return ( <div> {this.state.loggedIn ? ( <div className="animated fadeIn"> <WhiteboardNav pen={() => this.setState({tool: 'pen'})} eraser={() => this.setState({tool: 'eraser'})} donut={() => this.setState({tool: 'donut'})} tunnel={() => this.setState({tool: 'tunnel'})} fan={() => this.setState({tool: 'fan'})} clear={this.handleOnClickClear} bringBack={this.bringBack} save={this.saveAnImage} increaseSize={this.increaseSize} decreaseSize={this.decreaseSize} destroy={this.destroy} /> <PickBackground backgrounde={this.state.canvasStyle.backgroundColor} chooseBGParentColor={this.chooseBG} /> <PickColor brushColor={this.state.brushColor} changeParentColor={event => this.setState({brushColor: event.target.value })} /> <div className='canvas-style'> <CanvasDraw {...this.state}/> </div> <div style={indent}> <Gallery data={this.state.data} className="painting"/> </div> </div> ) : ( <div> <Login /> </div> )} </div> ) } };
client/node_modules/redux-form/es/ConnectedFields.js
Dans-labs/dariah
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import createFieldProps from './createFieldProps'; import plain from './structure/plain'; import onChangeValue from './events/onChangeValue'; import validateComponentProp from './util/validateComponentProp'; var propsToNotUpdateFor = ['_reduxForm']; var createConnectedFields = function createConnectedFields(structure) { var deepEqual = structure.deepEqual, getIn = structure.getIn, size = structure.size; var getSyncError = function getSyncError(syncErrors, name) { // Because the error for this field might not be at a level in the error structure where // it can be set directly, it might need to be unwrapped from the _error property return plain.getIn(syncErrors, name + "._error") || plain.getIn(syncErrors, name); }; var getSyncWarning = function getSyncWarning(syncWarnings, name) { var warning = getIn(syncWarnings, name); // Because the warning for this field might not be at a level in the warning structure where // it can be set directly, it might need to be unwrapped from the _warning property return warning && warning._warning ? warning._warning : warning; }; var ConnectedFields = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(ConnectedFields, _React$Component); function ConnectedFields(props) { var _this; _this = _React$Component.call(this, props) || this; _this.onChangeFns = {}; _this.onFocusFns = {}; _this.onBlurFns = {}; _this.ref = React.createRef(); _this.prepareEventHandlers = function (_ref) { var names = _ref.names; return names.forEach(function (name) { _this.onChangeFns[name] = function (event) { return _this.handleChange(name, event); }; _this.onFocusFns[name] = function () { return _this.handleFocus(name); }; _this.onBlurFns[name] = function (event) { return _this.handleBlur(name, event); }; }); }; _this.handleChange = function (name, event) { var _this$props = _this.props, dispatch = _this$props.dispatch, parse = _this$props.parse, _reduxForm = _this$props._reduxForm; var value = onChangeValue(event, { name: name, parse: parse }); dispatch(_reduxForm.change(name, value)); // call post-change callback if (_reduxForm.asyncValidate) { _reduxForm.asyncValidate(name, value, 'change'); } }; _this.handleFocus = function (name) { var _this$props2 = _this.props, dispatch = _this$props2.dispatch, _reduxForm = _this$props2._reduxForm; dispatch(_reduxForm.focus(name)); }; _this.handleBlur = function (name, event) { var _this$props3 = _this.props, dispatch = _this$props3.dispatch, parse = _this$props3.parse, _reduxForm = _this$props3._reduxForm; var value = onChangeValue(event, { name: name, parse: parse }); // dispatch blur action dispatch(_reduxForm.blur(name, value)); // call post-blur callback if (_reduxForm.asyncValidate) { _reduxForm.asyncValidate(name, value, 'blur'); } }; _this.prepareEventHandlers(props); return _this; } var _proto = ConnectedFields.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var _this2 = this; if (this.props.names !== nextProps.names && (size(this.props.names) !== size(nextProps.names) || nextProps.names.some(function (nextName) { return !_this2.props._fields[nextName]; }))) { // names has changed. The cached event handlers need to be updated this.prepareEventHandlers(nextProps); } }; _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { var _this3 = this; var nextPropsKeys = Object.keys(nextProps); var thisPropsKeys = Object.keys(this.props); // if we have children, we MUST update in React 16 // https://twitter.com/erikras/status/915866544558788608 return !!(this.props.children || nextProps.children || nextPropsKeys.length !== thisPropsKeys.length || nextPropsKeys.some(function (prop) { return !~propsToNotUpdateFor.indexOf(prop) && !deepEqual(_this3.props[prop], nextProps[prop]); })); }; _proto.isDirty = function isDirty() { var _fields = this.props._fields; return Object.keys(_fields).some(function (name) { return _fields[name].dirty; }); }; _proto.getValues = function getValues() { var _fields = this.props._fields; return Object.keys(_fields).reduce(function (accumulator, name) { return plain.setIn(accumulator, name, _fields[name].value); }, {}); }; _proto.getRenderedComponent = function getRenderedComponent() { return this.ref.current; }; _proto.render = function render() { var _this4 = this; var _this$props4 = this.props, component = _this$props4.component, forwardRef = _this$props4.forwardRef, _fields = _this$props4._fields, _reduxForm = _this$props4._reduxForm, rest = _objectWithoutPropertiesLoose(_this$props4, ["component", "forwardRef", "_fields", "_reduxForm"]); var sectionPrefix = _reduxForm.sectionPrefix, form = _reduxForm.form; var _Object$keys$reduce = Object.keys(_fields).reduce(function (accumulator, name) { var connectedProps = _fields[name]; var _createFieldProps = createFieldProps(structure, name, _extends({}, connectedProps, rest, { form: form, onBlur: _this4.onBlurFns[name], onChange: _this4.onChangeFns[name], onFocus: _this4.onFocusFns[name] })), custom = _createFieldProps.custom, fieldProps = _objectWithoutPropertiesLoose(_createFieldProps, ["custom"]); accumulator.custom = custom; var fieldName = sectionPrefix ? name.replace(sectionPrefix + ".", '') : name; return plain.setIn(accumulator, fieldName, fieldProps); }, {}), custom = _Object$keys$reduce.custom, props = _objectWithoutPropertiesLoose(_Object$keys$reduce, ["custom"]); if (forwardRef) { props.ref = this.ref; } return React.createElement(component, _extends({}, props, custom)); }; return ConnectedFields; }(React.Component); ConnectedFields.propTypes = { component: validateComponentProp, _fields: PropTypes.object.isRequired, props: PropTypes.object }; var connector = connect(function (state, ownProps) { var names = ownProps.names, _ownProps$_reduxForm = ownProps._reduxForm, initialValues = _ownProps$_reduxForm.initialValues, getFormState = _ownProps$_reduxForm.getFormState; var formState = getFormState(state); return { _fields: names.reduce(function (accumulator, name) { var initialState = getIn(formState, "initial." + name); var initial = initialState !== undefined ? initialState : initialValues && getIn(initialValues, name); var value = getIn(formState, "values." + name); var syncError = getSyncError(getIn(formState, 'syncErrors'), name); var syncWarning = getSyncWarning(getIn(formState, 'syncWarnings'), name); var submitting = getIn(formState, 'submitting'); var pristine = value === initial; accumulator[name] = { asyncError: getIn(formState, "asyncErrors." + name), asyncValidating: getIn(formState, 'asyncValidating') === name, dirty: !pristine, initial: initial, pristine: pristine, state: getIn(formState, "fields." + name), submitError: getIn(formState, "submitErrors." + name), submitFailed: getIn(formState, 'submitFailed'), submitting: submitting, syncError: syncError, syncWarning: syncWarning, value: value, _value: ownProps.value // save value passed in (for radios) }; return accumulator; }, {}) }; }, undefined, undefined, { forwardRef: true }); return connector(ConnectedFields); }; export default createConnectedFields;
src/js/views/Library/Tracks.js
jaedb/Iris
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import TrackList from '../../components/TrackList'; import Header from '../../components/Header'; import DropdownField from '../../components/Fields/DropdownField'; import FilterField from '../../components/Fields/FilterField'; import LazyLoadListener from '../../components/LazyLoadListener'; import Icon from '../../components/Icon'; import * as coreActions from '../../services/core/actions'; import * as uiActions from '../../services/ui/actions'; import * as mopidyActions from '../../services/mopidy/actions'; import * as spotifyActions from '../../services/spotify/actions'; import { sortItems, applyFilter, arrayOf } from '../../util/arrays'; import Button from '../../components/Button'; import { i18n, I18n } from '../../locale'; import Loader from '../../components/Loader'; import { makeLibrarySelector, makeProcessProgressSelector, getLibrarySource, makeProvidersSelector, getSortSelector, } from '../../util/selectors'; const SORT_KEY = 'library_tracks'; const processKeys = [ 'MOPIDY_GET_LIBRARY_TRACKS', 'SPOTIFY_GET_LIBRARY_TRACKS', ]; class Tracks extends React.Component { constructor(props) { super(props); this.state = { filter: '', }; } componentDidMount() { const { uiActions: { setWindowTitle, }, } = this.props; setWindowTitle(i18n('library.tracks.title')); this.getLibraries(); } componentDidUpdate = ({ source: prevSource }) => { const { source } = this.props; if (source !== prevSource) { this.getLibraries(); } } refresh = () => { const { uiActions: { hideContextMenu } } = this.props; hideContextMenu(); this.getLibraries(true); } cancelRefresh = () => { const { uiActions: { hideContextMenu, cancelProcess } } = this.props; hideContextMenu(); cancelProcess(processKeys); } getLibraries = (forceRefetch = false) => { const { source, providers, coreActions: { loadLibrary, }, } = this.props; let uris = []; if (source === 'all') { uris = providers.map((p) => p.uri); } else { uris.push(source); } uris.forEach((uri) => loadLibrary(uri, 'tracks', { forceRefetch })); }; handleContextMenu = (e, item) => { const { uiActions: { showContextMenu, }, } = this.props; showContextMenu({ e, context: 'album', uris: [item.uri], items: [item], }); } onSortChange = (field) => { const { sortField, sortReverse, uiActions: { setSort, hideContextMenu, }, } = this.props; let reverse = false; if (field !== null && sortField === field) { reverse = !sortReverse; } setSort(SORT_KEY, field, reverse); hideContextMenu(); } playAll = () => { const { sortField, sortReverse, mopidyActions: { playURIs, }, uiActions: { hideContextMenu, }, } = this.props; let { tracks } = this.props; const { filter } = this.state; if (!tracks || !tracks.length) return; if (sortField) { tracks = sortItems(tracks, sortField, sortReverse); } if (filter && filter !== '') { tracks = applyFilter('name', filter, tracks); } playURIs({ uris: arrayOf('uri', tracks) }); hideContextMenu(); } renderView = () => { const { sortField, sortReverse, loading_progress, } = this.props; const { filter, } = this.state; let { tracks } = this.props; if (loading_progress) { return <Loader body loading progress={loading_progress} />; } if (sortField) { tracks = sortItems(tracks, sortField, sortReverse); } if (filter && filter !== '') { tracks = applyFilter('name', filter, tracks); } return ( <section className="content-wrapper"> <TrackList context={{ name: 'Tracks', }} tracks={tracks} /> </section> ); } render = () => { const { source, providers, sortField, sortReverse, uiActions, loading_progress, } = this.props; const { filter, } = this.state; const sort_options = [ { value: null, label: i18n('fields.filters.as_loaded'), }, { value: 'name', label: i18n('fields.filters.name'), }, { value: 'artist', label: i18n('fields.filters.artist'), }, { value: 'album', label: i18n('fields.filters.album'), }, ]; const options = ( <> <FilterField initialValue={filter} handleChange={(value) => this.setState({ filter: value })} onSubmit={() => uiActions.hideContextMenu()} /> <DropdownField icon="swap_vert" name={i18n('fields.sort')} value={sortField} valueAsLabel options={sort_options} selected_icon={sortField ? (sortReverse ? 'keyboard_arrow_up' : 'keyboard_arrow_down') : null} handleChange={this.onSortChange} /> <DropdownField icon="cloud" name={i18n('fields.source')} value={source} valueAsLabel options={[ { value: 'all', label: i18n('fields.filters.all'), }, ...providers.map((p) => ({ value: p.uri, label: p.title })), ]} handleChange={ (val) => { uiActions.set({ library_tracks_source: val }); uiActions.hideContextMenu(); } } /> <Button onClick={this.playAll} noHover discrete tracking={{ category: 'LibraryTracks', action: 'Play' }} > <Icon name="play_circle_filled" /> <I18n path="actions.play_all" /> </Button> <Button noHover discrete onClick={loading_progress ? this.cancelRefresh : this.refresh} tracking={{ category: 'LibraryTracks', action: 'Refresh' }} > {loading_progress ? <Icon name="close" /> : <Icon name="refresh" /> } {loading_progress ? <I18n path="actions.cancel" /> : <I18n path="actions.refresh" /> } </Button> </> ); return ( <div className="view library-tracks-view"> <Header options={options} uiActions={uiActions}> <Icon name="album" type="material" /> <I18n path="library.tracks.title" /> </Header> {this.renderView()} </div> ); } } const librarySelector = makeLibrarySelector('tracks'); const processProgressSelector = makeProcessProgressSelector(processKeys); const providersSelector = makeProvidersSelector('tracks'); const mapStateToProps = (state) => { const [sortField, sortReverse] = getSortSelector(state, SORT_KEY, null); return { loading_progress: processProgressSelector(state), mopidy_uri_schemes: state.mopidy.uri_schemes, tracks: librarySelector(state, 'tracks'), view: state.ui.library_tracks_view, source: getLibrarySource(state, 'tracks'), providers: providersSelector(state), sortField, sortReverse, }; }; const mapDispatchToProps = (dispatch) => ({ coreActions: bindActionCreators(coreActions, dispatch), uiActions: bindActionCreators(uiActions, dispatch), mopidyActions: bindActionCreators(mopidyActions, dispatch), spotifyActions: bindActionCreators(spotifyActions, dispatch), }); export default connect(mapStateToProps, mapDispatchToProps)(Tracks);
src/components/DeveloperMenu.android.js
jiawang1/hoenixN
import React from 'react'; import * as snapshot from '../utils/snapshot'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; /** * Simple developer menu, which allows e.g. to clear the app state. * It can be accessed through a tiny button in the bottom right corner of the screen. * ONLY FOR DEVELOPMENT MODE! */ const DeveloperMenu = React.createClass({ displayName: 'DeveloperMenu', getInitialState() { return {visible: false}; }, showDeveloperMenu() { this.setState({isVisible: true}); }, async clearState() { await snapshot.clearSnapshot(); console.warn('(╯°□°)╯︵ ┻━┻ \nState cleared, Cmd+R to reload the application now'); this.closeMenu(); }, closeMenu() { this.setState({isVisible: false}); }, renderMenuItem(text, onPress) { return ( <TouchableOpacity key={text} onPress={onPress} style={styles.menuItem} > <Text style={styles.menuItemText}>{text}</Text> </TouchableOpacity> ); }, render() { if (!__DEV__) { return null; } if (!this.state.isVisible) { return ( <TouchableOpacity style={styles.circle} onPress={this.showDeveloperMenu} /> ); } const buttons = [ this.renderMenuItem('Clear state', this.clearState), this.renderMenuItem('Cancel', this.closeMenu) ]; return ( <View style={styles.menu}> {buttons} </View> ); } }); const styles = StyleSheet.create({ circle: { position: 'absolute', bottom: 5, right: 5, width: 10, height: 10, borderRadius: 5, backgroundColor: '#fff' }, menu: { backgroundColor: 'white', position: 'absolute', left: 0, right: 0, bottom: 0 }, menuItem: { flex: 1, flexDirection: 'row', alignItems: 'center', borderTopWidth: 1, borderTopColor: '#eee', padding: 10, height: 60 }, menuItemText: { fontSize: 20 } }); export default DeveloperMenu;
examples/with-app-layout/pages/_app.js
BlancheXu/test
import React from 'react' import App from 'next/app' class Layout extends React.Component { render () { const { children } = this.props return <div className='layout'>{children}</div> } } export default class MyApp extends App { render () { const { Component, pageProps } = this.props return ( <Layout> <Component {...pageProps} /> </Layout> ) } }
src/svg-icons/image/timelapse.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimelapse = (props) => ( <SvgIcon {...props}> <path d="M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); ImageTimelapse = pure(ImageTimelapse); ImageTimelapse.displayName = 'ImageTimelapse'; ImageTimelapse.muiName = 'SvgIcon'; export default ImageTimelapse;
src/index.js
DinoJay/cateract_app
import * as d3 from 'd3'; import React from 'react'; import ReactDOM from 'react-dom'; import 'font-awesome/css/font-awesome.css'; // import _ from 'lodash' import _ from 'lodash'; // import $ from 'jquery'; // import { introJs } from 'intro.js'; // delete for web build // import 'cordova'; // import 'intro.js/introjs.css'; // import 'cordova_plugins'; import './global_styles/app.scss'; import Visualization from './components/Visualization'; import Collapsible from './components/Collapsible'; import Home from './components/Home'; const timeFormatStr = '%d/%m/%Y %H:%M'; const parseDate = d3.timeParse(timeFormatStr); function preprocess(d) { d.initProtSel = Object.assign({}, d.protSel); d.date = parseDate(d.date); if (d.date === null) console.log('date null', d); return d; } class App extends React.Component { constructor(props) { // Pass props to parent class super(props); this.selectionHandler = this._selectionHandler.bind(this); this.dataChangeHandler = this._dataChangeHandler.bind(this); this.dataWipeHandler = this._dataWipeHandler.bind(this); this.operationRemoveHandler = this._operationRemoveHandler.bind(this); // Set initial state const stringData = localStorage.getItem('dataHHH'); console.log('stringData', stringData); let data = []; if (stringData !== null) { const rawData = JSON.parse(stringData); const newData = _.cloneDeep(rawData).map(preprocess).sort((a, b) => a.date - b.date); data = _.cloneDeep(newData); } else { localStorage.setItem('dataHHH', JSON.stringify([])); } this.state = { data, eye: true, aggrSel: false, threshhold: 0.4, timeBounds: [new Date(-8640000000000000), new Date()], home: data.length === 0 }; } componentDidMount() { if (this.state.data.length === 0) { $(() => { $('[data-toggle="tooltip"]').tooltip(); }); $('.tooltip-holder').tooltip('toggle'); } } _selectionHandler({ eye, cumulated }) { console.log('cumulated', cumulated); this.setState({ eye, cumulated }); } _dataChangeHandler(newData) { const rawData = JSON.parse(localStorage.getItem('dataHHH')); const newRawData = rawData.concat(newData); newRawData.forEach((d, i) => (d.id = i)); localStorage.setItem('dataHHH', JSON.stringify(newRawData)); const realData = this.state.data.concat(newData.map(preprocess)) .sort((a, b) => a.date - b.date); this.setState({ data: realData, home: realData.length === 0 }); } _dataWipeHandler() { localStorage.setItem('dataHHH', JSON.stringify([])); this.setState({ data: [], home: true }); } _operationRemoveHandler(ids) { console.log('operation remove', ids); if (ids.length === 0) return; const rawData = JSON.parse(localStorage.getItem('dataHHH')); const newData = rawData.filter(d => !ids.includes(d.id)); localStorage.setItem('dataHHH', JSON.stringify(newData)); const realData = newData.map(preprocess) .sort((a, b) => a.date - b.date); this.setState({ data: realData }); } // TODO: change later! render() { console.log('render', this.state.timeBounds); const newData = this.state.data.filter((d) => { const newDate = d.date.setHours(12); return newDate >= this.state.timeBounds[0] && newDate <= this.state.timeBounds[1]; }); return ( <div style={{ maxWidth: 500, margin: 'auto' }}> <Collapsible data={newData} eye={this.state.eye} dataWipeHandler={this.dataWipeHandler} dataChangeHandler={this.dataChangeHandler} selectionHandler={this.selectionHandler} operationRemoveHandler={this.operationRemoveHandler} homeHandler={() => this.setState({ home: !this.state.home })} active={this.state.home} /> { this.state.home ? <Home /> : <Visualization timeChange={d => this.setState({ timeBounds: d })} {...this.state} /> } </div> ); } } window.onload = ReactDOM.render(<App />, document.getElementById('app')); // const app = { // // visualization Constructor // initialize() { // document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); // }, // // // deviceready Event Handler // // // // Bind any cordova events here. Common events are: // // 'pause', 'resume', etc. // onDeviceReady() { // ReactDOM.render(<App />, document.getElementById('app')); // }, // // // Update DOM on a Received Event // receivedEvent() { // } // }; // // app.initialize();
app/components/List/index.js
acebusters/ab-web
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import WithLoading from '../WithLoading'; import ListItem from '../ListItem'; const Wrapper = styled.div` overflow-y: auto; `; const Table = styled.table` border-collapse: collapse; background-color: transparent; `; const TableStyled = styled(Table)` width: 100%; max-width: 100%; margin-bottom: 1rem; & th { padding: 0.75rem; vertical-align: top; border-top: 1px solid #eceeef; } & thead th { vertical-align: bottom; border-bottom: 2px solid #eceeef; } & tbody + tbody { border-top: 2px solid #eceeef; } & & { background-color: #fff; } `; const SortButton = styled.a` -webkit-user-select: none; cursor: pointer; color: inherit; span { text-decoration: underline; } `; export const TableStriped = styled(TableStyled)` & tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); } `; class List extends React.Component { constructor(props) { super(props); this.state = { sortBy: null, // column index sortDir: -1, // 1 — ascending, -1 — descending }; } sortedItems() { const { items } = this.props; const { sortBy, sortDir } = this.state; if (items && sortBy) { return items.sort((a, b) => (a[sortBy] - b[sortBy]) * sortDir); } return items; } handleHeaderClick(i) { this.setState(({ sortBy, sortDir }) => ({ sortBy: i, sortDir: sortBy === i ? sortDir * -1 : sortDir, })); } render() { const { headers, sortableColumns = [], noDataMsg = 'No Data', columnsStyle = {} } = this.props; const { sortBy, sortDir } = this.state; const items = this.sortedItems(); return ( <Wrapper> <TableStriped> <thead> <tr> {headers && headers.map((header, i) => { const sortable = sortableColumns.indexOf(i) !== -1; return ( <th key={i} style={columnsStyle[i]}> {!sortable && header} {sortable && <SortButton onClick={() => this.handleHeaderClick(i)}> <span>{header}</span> {sortBy === i && sortDir === 1 && ' ▲'} {sortBy === i && sortDir === -1 && ' ▼'} </SortButton> } </th> ); })} {!headers && <th />} </tr> </thead> {items && items.length > 0 && ( <tbody> {items.map((item, i) => ( <ListItem key={i} values={item} columnsStyle={columnsStyle} /> ))} </tbody> )} </TableStriped> <WithLoading isLoading={!items} styles={{}} > {items && items.length === 0 && ( <div style={{ textAlign: 'center' }}> {noDataMsg} </div> )} </WithLoading> </Wrapper> ); } } List.propTypes = { items: PropTypes.arrayOf(PropTypes.node), headers: PropTypes.arrayOf(PropTypes.node), sortableColumns: PropTypes.arrayOf(PropTypes.number), columnsStyle: PropTypes.object, noDataMsg: PropTypes.string, }; export default List;
docs/src/examples/collections/Grid/Variations/GridExampleFloated.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleFloated = () => ( <Grid> <Grid.Column floated='left' width={5}> <Image src='/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column floated='right' width={5}> <Image src='/images/wireframe/paragraph.png' /> </Grid.Column> </Grid> ) export default GridExampleFloated
components/Internship/NextSteps.js
uclaacm/website
import React from 'react'; function NextSteps(props) { const { image, name, info} = props; return ( <> <div style={{border: '1px solid grey', margin: '5px', borderRadius: '5px', padding: '15px'}}> {/* eslint-disable-next-line @next/next/no-img-element */} <img src={image} alt={name} height='30px'/> <p>{info}</p> </div> </> // <button className={styles['committee-card']} onClick={() => setFlipped(!isFlipped)} role='tab'> // <div className={`${styles['next-steps-card-inner']} ${styles[isFlipped ? null : 'is-flipped']}`}> // <div className={styles['next-steps-card-face']}> // <Image // src={image} // alt={`${name}'s card. Click to see more information.`} // layout='fill' // /> // </div> // <div className={`${styles['next-steps-card-face']}`}> // <h3 className={styles['card-info-name']}>{name}</h3> // <p>{info}</p> // </div> // </div> // </button> ); } export default NextSteps;
classic/src/scenes/wbfa/generated/FASDownload.pro.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faDownload } from '@fortawesome/pro-solid-svg-icons/faDownload' export default class FASDownload extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faDownload} />) } }
src/components/selectSite/SelectSiteView.js
timLoewel/sites
/** * Created by tim on 10/03/17. */ import {connect} from 'react-redux'; import React from 'react'; import { AppRegistry, AsyncStorage, Button, StyleSheet, Text, View, } from 'react-native'; class SelectSiteView extends React.Component { static navigationOptions = { tabBar: { label: 'SelectSite', // visible: false, }, } render() { return ( <Button onPress={() => this.props.navigation.navigate('NewPhoto')} title="take Photo" /> ); } } const mapStateToProps = state => ({ }); function bindAction(dispatch) { return { }; } export default connect(mapStateToProps, bindAction)(SelectSiteView);
test/index.js
theuprising/react-animable
import React from 'react' import { test } from 'ava' import { shallow } from 'enzyme' import ReactAnimable from '../' test('ReactAnimable renders without crashing', t => { t.notThrows(() => shallow(<ReactAnimable />)) }) test('ReactAnimable accepts className', t => { const c = shallow(<ReactAnimable className='react-animable' />) t.true(c.hasClass('react-animable')) })
blueocean-material-icons/src/js/components/svg-icons/hardware/keyboard-arrow-down.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareKeyboardArrowDown = (props) => ( <SvgIcon {...props}> <path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z"/> </SvgIcon> ); HardwareKeyboardArrowDown.displayName = 'HardwareKeyboardArrowDown'; HardwareKeyboardArrowDown.muiName = 'SvgIcon'; export default HardwareKeyboardArrowDown;
client-src/components/parts/InspectionPreview.js
Neil-G/InspectionLog
// @flow import React, { Component } from 'react'; import { Link } from 'react-router' require('./../../../public/custom.css') import moment from 'moment' class InspectionPreview extends Component { render() { const { inspection: { createdAt, updatedAt, _id, DOB, address: { line1, line2, city, state, zip } } } = this.props return ( <li className='inspection-preview'> <div style={{ float: 'right', fontSize: 'smaller' }}> created: {moment(createdAt).format('M/D/YY')} </div> <div style={{ float: 'right', clear: 'both', fontSize: 'smaller' }}> last updated: {moment(updatedAt).format('M/D/YY')} </div> <div> <div style={{ fontSize: 'larger', fontWeight: 'bold', marginBottom: '12px'}} > DOB#: <Link to={`/inspections/${_id}`}> { DOB } </Link> </div> <div className='tight-lines'>{line1}</div> <div className='tight-lines'> {line2}</div> <div className='tight-lines'>{city}, {state}, {zip}</div> </div> </li> ); } } export default InspectionPreview
EquationScreen.js
stevenpan91/ChemicalEngineerHelper
'use strict' import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button, TouchableHighlight, TouchableOpacity, Navigator } from 'react-native'; class EquationScreen extends Component { render() { return ( <Navigator renderScene={this.renderScene.bind(this)} navigator={this.props.navigator} navigationBar={ <Navigator.NavigationBar style={{backgroundColor: '#246dd5'}} routeMapper={NavigationBarRouteMapper} /> } /> ); } renderScene(route, navigator) { return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <TouchableOpacity onPress={this.gotoCalculation.bind(this)}> <Text>Density</Text> </TouchableOpacity> </View> ); } gotoCalculation() { this.props.navigator.push({ id: 'CalcScreen', sceneConfig: Navigator.SceneConfigs.FloatFromBottom, }); } // gotoMain() { // this.props.navigator.push({ // id: 'MainScreen', // sceneConfig: Navigator.SceneConfigs.FloatFromBottom, // }); // } } var NavigationBarRouteMapper = { LeftButton(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.parentNavigator.pop()}> <Text style={{color: 'white', margin: 10,}}> Back </Text> </TouchableOpacity> ); }, RightButton(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.parentNavigator.push({id: 'unknown'})}> <Text style={{color: 'white', margin: 10,}}> Test </Text> </TouchableOpacity> ); }, Title(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.push({ id: 'MainScreen', sceneConfig: Navigator.SceneConfigs.FloatFromBottom, })}> <Text style={{color: 'white', margin: 10, fontSize: 16}}> Main Page </Text> </TouchableOpacity> ); } }; module.exports = EquationScreen;
app/components/Sidebar/index.js
medevelopment/UMA
import React from 'react'; import {FormattedMessage} from 'react-intl'; import {IndexRoute, browserHistory} from 'react-router'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import SearchBar from '../SearchBar'; import UserBox from '../UserBox'; import HeaderLink from './HeaderLink'; import messages from './messages'; class SideBar extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <HeaderLink to="/"> DASHBOARD </HeaderLink> <HeaderLink to="/properties"> PROPERTIES </HeaderLink> <HeaderLink to="/investors"> INVESTORS </HeaderLink> <HeaderLink to="/tenants"> TENANTS </HeaderLink> <HeaderLink to="/suppliers"> SUPPLIERS </HeaderLink> <HeaderLink to="/service"> MAINTENANCE </HeaderLink> <HeaderLink to="/updates"> UPDATES </HeaderLink> </div> ); } } export default SideBar;
src/components/Pictos/Logo.js
Skoli-Code/DerangeonsLaChambre
import React from 'react'; import SvgIcon from 'material-ui/SvgIcon'; import * as _ from 'lodash'; const Logo = (props)=>{ const useWhite = props.useWhite; const path1Color = useWhite ? 'white': '#051440'; const path2Color = useWhite ? 'white': '#ec1920'; const _props = _.pick(props, _.keys(props).filter(k=>k!='useWhite')); return ( <SvgIcon {..._props} viewBox="0 0 770 770"> <g transform="matrix(0.88751309,0,0,0.90283159,-189.06802,228.13917)"> <g transform="matrix(0.89154563,0,0,0.89154563,70.142893,-121.24877)"> <path fill={path1Color} d="m558.9,303.87c0.611-16.97-0.938-50.974,0.075-67.926,0.185-3.101-0.243-9.849,1.644-12.317,0.967-1.265,4.33-2.873,5.87-2.47,6.033,1.578,12.719,14.023,15.309,19.696,4.545,9.955,5.674,28.602,5.452,43.434-0.222,14.774,1.448,33.262,1.498,44.357,0.036,8.115-1.323,24.31-1.596,32.42-0.695,20.722-0.991,55.28-1.605,82.917-0.045,2.022-0.021,5.208-1.98,6.024-2.48,1.034-5.758-1.698-7.099-3.62-6.344-9.093-10.246-19.329-12.572-30.185-6.709-31.311-7.892-71.123-6.578-94.858,0.241-4.379,1.424-13.089,1.582-17.472zm-64.849-61.74c0.204-3.942,1.301-7.858,2.185-11.741,0.938-4.119,4.229-4.436,7.493-3.835,9.396,1.729,13.858,8.699,16.557,16.882,3.898,11.818,5.15,24.09,4.282,36.475-2.29,32.707-4.881,65.393-7.157,98.101-1.106,15.889,0.174,35.762,1.339,47.613,0.145,1.478,0.482,4.026,0.112,5.939-1.406,7.284-8.085,9.722-13.761,5.038-4.379-3.614-6.638-8.353-8.067-13.933-4.523-17.672-6.952-35.565-7.006-53.785-0.054-18.137-0.412-40.814-0.012-54.411,0.535-18.106,2.788-48.24,4.035-72.343zm-45.059,112.13c-0.788,29.456,2.397,56.707-1.929,78.38-0.294,1.474-0.811,5.021-2.2,5.595-1.771,0.732-5.66-1.722-7.022-3.07-7.922-7.84-12.258-27.259-14.743-42.073-3.307-19.719-4.811-39.554-4.117-59.635,1.126-32.611,1.41-65.25,2.134-97.875,0.081-3.644,0.532-7.305,1.137-10.904,0.533-3.175,2.905-4.189,5.607-2.876,6.4,3.11,12.087,9.885,14.025,14.551,3.198,7.699,5.873,24.383,6.612,32.687,1.106,12.425,1.966,49.859,1.966,49.859s-1.243,26.896-1.47,35.361zm-71.68-13.07c-0.887,31.628-1.831,64.435-2.694,97.244-0.108,4.106-1.645,7.151-5.49,8.653-4.07,1.59-6.588-1.052-8.939-3.767-5.396-6.233-6.554-14.086-8.073-21.739-6.246-31.476-8.579-63.358-9.095-95.364-0.46-28.485-1.612-64.15-0.18-85.469,0.475-7.073-0.252-22.206,3.656-28.12,0.805-1.219,3.589-3.169,5.035-2.966,7.398,1.041,17.427,14.901,20.568,21.68,7.865,16.98,5.407,49.641,5.226,74.668-0.083,11.33-0.014,22.662-0.014,35.18zm271.77-279.63s-330.73,82.945-337.98,84.783c-4.979,1.262-5.144,4.3565-1,7.3125,4.321,3.084,8.3905,5.9192,12.688,8.9062,2.615,1.818,3.6562,4.924,3.6562,6.875v29.188h322.63l0.00044-137.06zm-328.52,401.32l-107.53,44.906v31.719h434.63v-76.625z"/> <path fill={path2Color} d="m953.48,243.78c-1.177,13.915-2.391,27.855-2.692,41.802-0.536,24.79-0.393,49.595-0.494,74.395-0.083,20.141,0.937,45.367-0.292,60.422-0.334,4.094-1.721,10.817-2.868,16.177-0.749,3.498-4.452,6.471-6.698,6.137-2.23-0.331-4.839-4.18-5.273-7.314-2.809-20.272-5.984-40.518-7.96-60.876-3.278-33.787-7.309-76.057-8.464-101.49-0.192-4.229-0.162-11.332,0.471-16.925,1.549-13.691,2.009-31.201,5.292-41.001,0.85-2.539,4.428-7.914,9.66-4.623,12.274,7.719,20.646,17.6,19.318,33.298zm-102.58-20.82c8.223-6.249,17.448,9.593,19.943,15.372,1.28,2.964,3.45,9.091,4.042,12.264,5.091,27.287,5.392,83.134,5.608,110.89,0.078,9.99-0.932,26.621-1.391,39.936-0.303,8.805-0.368,17.642-1.296,26.385-0.277,2.609-2.969,5.07-4.891,7.31-0.403,0.469-2.728-0.145-3.462-0.629-0.511-0.337-1.151-1.238-1.415-1.996-5.064-14.567-12.176-28.717-12.876-44.351-2.145-47.915,0.596-108.32-5.377-143.79-0.888-5.28-5.144-16.635,1.115-21.391zm-43.248,97.238c0.442,27.89-4.101,57.184-6.036,86.557-0.456,6.929-0.012,13.914-0.387,20.852-0.152,2.813-0.75,5.991-2.263,8.257-2.905,4.353-6.241,3.715-9.094-0.798-8.393-13.276-9.892-28.412-11.825-43.399-6.86-53.202-4.599-106.7-4.947-160.11-0.01-1.487,0.093-3.01,0.408-4.459,1.333-6.123,7.857-5.524,10.174-4.064,7.771,4.898,15.688,19.605,17.24,32.447,2.537,20.967,6.368,41.897,6.73,64.713zm-106.95-105.44c8.091-5.818,18.504,8.156,22.212,13.492,4.019,5.784,7.054,17.372,9.006,26.694,5.806,27.724,7.094,55.851,6.478,83.943-0.582,26.558-3.388,53.065-5.053,79.604-0.29,4.616,0.011,9.304,0.439,13.922,0.44,4.756-1.593,8.385-6.728,9.959-4.622,1.416-5.834-2.701-6.886-5.509-7.313-19.51-16.316-38.39-16.42-60.115-0.127-26.437-1.738-52.867-2.75-79.299-0.809-21.122-1.888-42.237-2.397-63.367-0.146-6.061-3.755-15.114,2.099-19.324zm-40.096,385.31v-137.06h319.45v29.188c0,1.951,1.0412,5.057,3.6562,6.875,4.297,2.987,8.3675,5.8232,12.688,8.9062,4.143,2.957,3.9478,6.0505-1.0312,7.3125zm-1.3442-401.31v-76.625h421.26v31.719l-107.53,44.906z"/> </g> </g> </SvgIcon> ); }; export default Logo;
wrappers/toml.js
tim-thimmaiah/iyla
import React from 'react' import toml from 'toml-js' import Helmet from 'react-helmet' import { config } from 'config' module.exports = React.createClass({ propTypes () { return { route: React.PropTypes.object, } }, render () { const data = this.props.route.page.data return ( <div> <Helmet title={`${config.siteTitle} | ${data.title}`} /> <h1>{data.title}</h1> <p>Raw view of toml file</p> <pre dangerouslySetInnerHTML={{ __html: toml.dump(data) }} /> </div> ) }, })
frontend/src/signup/components/ProgressSteps.js
rabblerouser/core
import React from 'react'; import { connect } from 'react-redux'; import { getProgress } from '../reducers'; import DetailsForm from './DetailsForm'; import Finished from './Finished'; const steps = [ null, <DetailsForm />, <Finished />, ]; export const ProgressSteps = ({ currentStep }) => steps[currentStep]; export default connect(state => ({ currentStep: getProgress(state) }))(ProgressSteps);
src/App/Body/Inputs/FileInput/index.js
ksmithbaylor/emc-license-summarizer
import React from 'react'; import RaisedButton from 'material-ui/lib/raised-button'; import FileHandler from './FileHandler'; export default function FileInput({ requestResults, style }) { return ( <div style={style.section}> <RaisedButton label="OPEN" primary linkButton onTouchTap={fileDecoded} style={style.button} > <FileHandler requestResults={requestResults} /> </RaisedButton> Open a license file from your computer </div> ); } function fileDecoded(event) { if (typeof window.ga === 'function') { ga('send', 'event', 'Decode', 'file'); } }
src/common/components/Home/HomeRender.js
minmaster/gig-native-web
'use strict'; import React from 'react'; import classNames from 'classnames'; var If = React.createClass({ render: function() { if (this.props.condition) { return this.props.children; } else { return false; } } }); export default function (props, state) { var list = []; this.state.items.map((item, i) => { var styleCont = { backgroundImage: 'url(src/images/'+item.image+')' } list.push( <li key={i} onClick={this.handleClick.bind(this, item, 'web')}> <div className="cont" style={styleCont}> <if condition={item.caption}> <div className='caption right'> <p>{item.caption}</p> <span></span> </div> </if> <h3 className="title">{item.title}</h3> <p className="subtitle">{item.subtitle}</p> </div> </li> ) }); return ( <div className='home-list'> <ul> {list} </ul> </div> ); }
src/TextField.js
kiloe/ui
import React from 'react'; import View from './View'; import CSS from './utils/css'; import ReactDOM from 'react-dom'; const rowsHeight = 32; CSS.register({ // TODO: scrap this, I was just playing with how to move the placeholder, it's webkit only so not great '.textField': { marginBottom: '6px', position: 'relative', }, '.textField input, .textField textarea': { border: 'none', flex: '1 1 auto', fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontSize: '1.3rem', padding: '0px', margin: '8px 0px 7px 0px', backgroundColor: 'transparent', color: 'inherit', lineHeight: '32px', opacity: '0.9', width: '100%', }, '.textField input:focus, .textField textarea:focus': { boxShadow: 'none', outline: 'none', backgroundPosition: '0 0', opacity: '1', }, '.textField input::-webkit-input-placeholder, .textField textarea::-webkit-input-placeholder': { transition: { all: CSS.transitions.swift, }, }, '.textField .error': { color: 'red', fontSize: '1rem', }, '.textField .characterCount': { fontSize: '1rem', textAlign: 'right', }, '.textField .icon': { padding: '11px', }, '.textField .placeholder': { position: 'absolute', top: '14px', fontSize: '1.3rem', transition: 'all 0.3s cubic-bezier(.64,.09,.08,1)', }, '.textField .placeholder.title': { transform: 'translateY(-20px)', fontSize: '1rem', }, '.textField .fieldContainer': { position: 'relative', }, '.textField hr.colorBorder': { borderStyle: 'none none solid', borderBottomWidth: '2px', position: 'absolute', width: '100%', bottom: '8px', margin: '0px', boxSizing: 'content-box', height: '0px', transform: 'scaleX(0)', transition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', }, '.textField hr.greyBorder': { border: 'none', borderBottom: 'solid 1px #e0e0e0', position: 'absolute', width: '100%', bottom: '8px', margin: '0', MozBoxSizing: 'content-box', boxSizing: 'content-box', height: '0', }, '.textField textarea': { width: '100%', resize: 'none', }, '.textField textarea.shadow': { overflow: 'hidden', position: 'absolute', opacity: 0, }, }); export default class TextField extends View { static propTypes = { ...View.propTypes, value: React.PropTypes.string, placeholder: React.PropTypes.string, name: React.PropTypes.string, multiLine: React.PropTypes.bool, type: React.PropTypes.string, rows: React.PropTypes.number, maxRows: React.PropTypes.number, //html's maxlength maxlength: React.PropTypes.number, required: React.PropTypes.bool, pattern: React.PropTypes.string, error: React.PropTypes.string, icon: React.PropTypes.oneOfType([ React.PropTypes.element, React.PropTypes.func, ]), // set a picker to use to choose a value (ie DatePicker, ColorPicker etc) picker: React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.node, ]), onChange: React.PropTypes.func, } static defaultProps = { ...View.defaultProps, value: '', placeholder: '', multiLine: false, type: 'text', rows: 1, required: false, onChange: function() { }, } constructor(...args){ super(...args); this.state = this.state || {}; this.state.value = ''; } componentDidMount(){ this.setState({ value: this.props.value, height: this.props.rows * rowsHeight }); if ( this.props.multiLine ) this._syncHeightWithShadow(); } getClassNames(){ let cs = super.getClassNames(); cs.textField = true; if ( this.props.icon ) cs.withIcon = true; return cs; } isInvalid(){ if ( this.props.required && this.state.value == '' ) return 'Required'; //required if ( this.state.value.length > this.props.maxlength ) return true; //no message, handled by counter //url if ( this.state.value.length > 0 && this.props.type == 'url' ) { let pattern = /^(http|https):\/\/(([a-zA-Z0-9$\-_.+!*'(),;:&=]|%[0-9a-fA-F]{2})+@)?(((25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|[1-9][0-9]|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|[1-9][0-9]|[0-9])){3})|localhost|([a-zA-Z0-9\-\u00C0-\u017F]+\.)+([a-zA-Z]{2,}))(:[0-9]+)?(\/(([a-zA-Z0-9$\-_.+!*'(),;:@&=]|%[0-9a-fA-F]{2})*(\/([a-zA-Z0-9$\-_.+!*'(),;:@&=]|%[0-9a-fA-F]{2})*)*)?(\?([a-zA-Z0-9$\-_.+!*'(),;:@&=\/?]|%[0-9a-fA-F]{2})*)?(\#([a-zA-Z0-9$\-_.+!*'(),;:@&=\/?]|%[0-9a-fA-F]{2})*)?)?$/; if( !pattern.test(this.state.value) ) return 'Invalid URL.'; } //number if ( this.state.value.length > 0 && this.props.type == 'number' ) { let pattern = /^[0-9\.\-]+$/; if( !pattern.test(this.state.value) ) return 'Invalid number.'; } //email if ( this.state.value.length > 0 && this.props.type == 'email' ) { let pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i; if( !pattern.test(this.state.value) ) return 'Invalid email address.'; } // TODO: this.props.pattern return false; } getBackgroundColor() { return 'transparent'; } getTextColor() { return this.getTheme({ paletteMode: 'grey' }).getColoredTextColor(false, this.getLayer(),this.getTopLayer(), 'primary'); } getHighlightColor() { if ( this.getTheme().getPaletteMode() == 'accent' ) return this.getTheme().getBackgroundColor(); else return this.getTheme({ paletteMode: 'primary' }).getBackgroundColor(); //the default } getLayer(){ return this.context.layer; } getRegisterLayerHandler(){ return; // don't bother registering text fields as layers } getRaise(){ return 0; } getPicker(){ if( !this.props.picker ){ return; } let props = { key:'picker', onCancel: () => { this.setState({showPicker: false, focus:false}); }, onSelected: (v) => { this.setState({value: v.toString(), showPicker: false, focus:false}); } }; if( this.props.picker instanceof Function ){ let Picker = this.props.picker; return <Picker {...props} />; } return React.cloneElement(this.props.picker, props); } getStyle(){ let style = super.getStyle(); return style; } // getIcon returns the icon as an element or undefined if no icon prop getIcon(){ if( !this.props.icon ){ return; } let props = { key:'icon', size:'intrinsic', outline: this.props.outline, color: ( this.state.focus ? this.getHighlightColor() : this.getTextColor() ), }; if( this.props.icon instanceof Function ){ let Icon = this.props.icon; return <Icon {...props} />; } return React.cloneElement(this.props.icon, props); } getError(){ if ( this.props.error ) return this.props.error; return this.isInvalid(); } handleChange = (event) => { this.setState({value: event.target.value}); if ( this.props.multiLine ) this._syncHeightWithShadow(event.target.value); this.props.onChange( event.target.value, event ); } onFocus = () => { this.setState({focus: true, showPicker: (this.props.picker !== undefined) }); } onBlur = () => { if( this.state.showPicker ){ console.log('showPicker onBlur'); return; } this.setState({focus: false}); } _syncHeightWithShadow(newValue, e) { let shadow = ReactDOM.findDOMNode(this.refs.shadow); if (newValue !== undefined) { shadow.value = newValue; } let newHeight = shadow.scrollHeight; if (this.props.maxRows > this.props.rows) { newHeight = Math.min(this.props.maxRows * rowsHeight, newHeight); } newHeight = Math.max(newHeight, rowsHeight); if (this.state.height !== newHeight) { this.setState({ height: newHeight, }); if (this.props.onHeightChange) { this.props.onHeightChange(e, newHeight); } } } render(){ let children = []; let greyColor = this.getTheme({ paletteMode: 'grey' }).getBackgroundColor(); let picker = this.getPicker(); if( this.state.showPicker && picker ){ children.push(picker); } let style = {}; let color = greyColor; let counterStyle = { color: color }; if ( this.isInvalid() ) { color = 'red'; counterStyle = { color: color }; } else if ( this.state.focus ) color = this.getHighlightColor(); style.color = this.getTextColor(); if ( this.props.multiLine ) style.height = this.state.height; let errorMsg = this.isInvalid(); let fieldGroup = []; if ( this.props.placeholder ) { let placeholder = <div key="placeholder" className={ 'placeholder' + ( this.state.focus || this.state.value.length > 0 ? ' title' : '' ) } style={{ color: color }}>{ this.props.placeholder }</div>; fieldGroup.push( placeholder ); } if ( this.props.multiLine ) { fieldGroup.push( <span key="textarea-container"> <textarea rows="1" key="input" value={this.state.value} name={this.props.name} type={this.props.type} required={this.props.required} pattern={this.props.pattern} onChange={this.handleChange} onFocus={this.onFocus} onBlur={this.onBlur} disabled={this.props.disabled} style={ style } ></textarea> <textarea className="shadow" ref="shadow" key="shadow" tabIndex="-1" rows={this.props.rows} readOnly={true} value={this.state.value} /> </span> ); } else { fieldGroup.push( <input key="input" value={this.state.value} name={this.props.name} type={this.props.type} required={this.props.required} pattern={this.props.pattern} onChange={this.handleChange} onFocus={this.onFocus} onBlur={this.onBlur} disabled={this.props.disabled} style={ style } /> ); } fieldGroup.push( <hr key="gborder" className="greyBorder" style={{ borderStyle: (this.props.disabled ? 'dashed' : 'solid' ), borderWidth: '1px' }} /> ); if (!this.props.disabled) fieldGroup.push( <hr key="cborder" className="colorBorder" style={{ borderColor: color, transform: 'scaleX(' + ( this.state.focus || errorMsg ? '1' : '0' ) + ')' }} /> ); let field = <View key="field" className="fieldContainer" theme={{ mode: 'transparent' }}>{ fieldGroup }</View>; //maxLength={this.props.maxlength} if( this.props.icon ){ children.push( <View key="icon" row style={{ justifyContent: 'space-between' }} theme={{ mode: 'transparent' }}>{ this.getIcon() }{ field }</View> ); } else children.push( field ); if ( errorMsg ) { children.push( <div key="err" className="error">{ errorMsg }</div> ); } if ( this.props.maxlength > 0 ) { children.push( <div key="cntr" className="characterCount" style={counterStyle}>{ this.state.value.length } / { this.props.maxlength }</div> ); } return super.render(children); } }
actor-apps/app-web/src/app/components/dialog/messages/Text.react.js
damoguyan8844/actor-platform
import _ from 'lodash'; import React from 'react'; import memoize from 'memoizee'; import emojify from 'emojify.js'; import emojiCharacters from 'emoji-named-characters'; import Markdown from '../../../utils/Markdown'; const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character)); emojify.setConfig({ mode: 'img', img_dir: 'assets/img/emoji' // eslint-disable-line }); const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function (name) { return name.replace(/\+/g, '\\+'); }); const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi'); const processText = function (text) { let markedText = Markdown.default(text); // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127 const noPTag = markedText.replace(/<p>/g, '<p> '); let emojifiedText = emojify .replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':')); return emojifiedText; }; const memoizedProcessText = memoize(processText, { length: 1000, maxAge: 60 * 60 * 1000, max: 10000 }); class Text extends React.Component { static propTypes = { content: React.PropTypes.object.isRequired, className: React.PropTypes.string }; constructor(props) { super(props); } render() { const { content, className } = this.props; const renderedContent = ( <div className={className} dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}> </div> ); return renderedContent; } } export default Text;
app/js/components/Profile.js
dYb/react-boilerplate
import React from 'react'; import { Link } from 'react-router'; export default class Profile extends React.Component { constructor(props) { super(props); } render(){ console.log('profile') return ( <div className="profile"> <h2>Profile</h2> <ul> <li><Link to="/">Home</Link></li> </ul> </div> ) } }
src/app/containers/Sidebar.js
GContaldi/node_chat
import React from 'react'; import { connect } from 'react-redux'; import Avatar from '../components/Avatar'; const Sidebar = (props) => ( <div data-component="Sidebar"> <ul> { props.users.map((user, index) => ( <li key={index} className="sidebar--username"> <Avatar username={user} /> {user} </li> )) } </ul> </div> ); Sidebar.propTypes = { users: React.PropTypes.arrayOf(React.PropTypes.string) }; const isUserPresent = (users, user) => { return users.indexOf(user) !== -1; }; const getUsersFromMessages = (messages) => { return messages.reduce((users, message) => { if (!isUserPresent(users, message.username)) { users.push(message.username); } return users; }, []); }; const mapStateToProps = (state) => { return { users: getUsersFromMessages(state.messages) }; }; export default connect(mapStateToProps)(Sidebar);
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
tsdl2013/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
docs/app/Examples/modules/Accordion/Types/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const AccordionTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Accordion' description='A standard Accordion.' examplePath='modules/Accordion/Types/AccordionExampleStandard' /> <ComponentExample title='Panels Prop' description='Accordion panels can be define using the `panels` prop.' examplePath='modules/Accordion/Types/AccordionExamplePanelsProp' > <Message info> Panel objects can define an <code>active</code> key to open/close the panel. {' '}They can also define an <code>onClick</code> key to be applied to the <code>Accordion.Title</code>. </Message> </ComponentExample> <ComponentExample title='Active Index' description='The `activeIndex` prop controls which panel is open.' examplePath='modules/Accordion/Types/AccordionExampleActiveIndex' > <Message info> An <code>active</code> prop on an {' '}<code>&lt;Accordion.Title&gt;</code> or <code>&lt;Accordion.Content&gt;</code> {' '}will override the <code>&lt;Accordion&gt;</code> <code>&lt;activeIndex&gt;</code> prop. </Message> </ComponentExample> <ComponentExample title='Styled' description='A styled accordion adds basic formatting.' examplePath='modules/Accordion/Types/AccordionExampleStyled' /> </ExampleSection> ) export default AccordionTypesExamples
src/components/AppRow.js
leanix/leanix-app-launchpad
import React from 'react' // eslint-disable-next-line no-unused-vars import AppBox from './AppBox' export default class AppRow extends React.Component { render () { const boxes = this.props.apps.map((app, index) => { return <AppBox app={app} key={index} /> }) return ( <div className="row"> {boxes} </div> ) } }
App/Containers/DeviceInfoScreen.js
okmttdhr/YoutuVote
// @flow // An All Components Screen is a great way to dev and quick-test components import React from 'react'; import { View, ScrollView, Text, Image, NetInfo } from 'react-native'; import DeviceInfo from 'react-native-device-info'; import { metrics, Images } from '../Themes'; import styles from './Styles/DeviceInfoScreenStyle'; const HARDWARE_DATA = [ {title: 'Device Manufacturer', info: DeviceInfo.getManufacturer()}, {title: 'Device Name', info: DeviceInfo.getDeviceName()}, {title: 'Device Model', info: DeviceInfo.getModel()}, {title: 'Device Unique ID', info: DeviceInfo.getUniqueID()}, {title: 'Device Locale', info: DeviceInfo.getDeviceLocale()}, {title: 'Device Country', info: DeviceInfo.getDeviceCountry()}, {title: 'User Agent', info: DeviceInfo.getUserAgent()}, {title: 'Screen Width', info: metrics.screenWidth}, {title: 'Screen Height', info: metrics.screenHeight}, ]; const OS_DATA = [ {title: 'Device System Name', info: DeviceInfo.getSystemName()}, {title: 'Device ID', info: DeviceInfo.getDeviceId()}, {title: 'Device Version', info: DeviceInfo.getSystemVersion()}, ]; const APP_DATA = [ {title: 'Bundle Id', info: DeviceInfo.getBundleId()}, {title: 'Build Number', info: DeviceInfo.getBuildNumber()}, {title: 'App Version', info: DeviceInfo.getVersion()}, {title: 'App Version (Readable)', info: DeviceInfo.getReadableVersion()}, ]; export default class DeviceInfoScreen extends React.Component { state: { isConnected: boolean, connectionInfo: Object | null, connectionInfoHistory: Array<any> } constructor(props: Object) { super(props); this.state = { isConnected: false, connectionInfo: null, connectionInfoHistory: [], }; } componentDidMount() { NetInfo.isConnected.addEventListener('change', this.setConnected); NetInfo.isConnected.fetch().done(this.setConnected); NetInfo.addEventListener('change', this.setConnectionInfo); NetInfo.fetch().done(this.setConnectionInfo); NetInfo.addEventListener('change', this.updateConnectionInfoHistory); // an example of how to display a custom Reactotron message // console.tron.display({ // name: 'SPECS', // value: { // hardware: fromPairs(map((o) => [o.title, o.info], HARDWARE_DATA)), // os: fromPairs(map((o) => [o.title, o.info], OS_DATA)), // app: fromPairs(map((o) => [o.title, o.info], APP_DATA)) // }, // preview: 'About this device...' // }) } componentWillUnmount() { NetInfo.isConnected.removeEventListener('change', this.setConnected); NetInfo.removeEventListener('change', this.setConnectionInfo); NetInfo.removeEventListener('change', this.updateConnectionInfoHistory); } setConnected = (isConnected: boolean) => { this.setState({isConnected}); } setConnectionInfo = (connectionInfo: Object) => { this.setState({connectionInfo}); } updateConnectionInfoHistory = (connectionInfo: Object) => { const connectionInfoHistory = this.state.connectionInfoHistory.slice(); connectionInfoHistory.push(connectionInfo); this.setState({connectionInfoHistory}); } netInfo() { return ([ {title: 'Connection', info: (this.state.isConnected ? 'Online' : 'Offline')}, {title: 'Connection Info', info: this.state.connectionInfo}, {title: 'Connection Info History', info: JSON.stringify(this.state.connectionInfoHistory)}, ]); } renderCard(cardTitle: string, rowData: Array<Object>) { return ( <View style={styles.cardContainer}> <Text style={styles.cardTitle}>{cardTitle.toUpperCase()}</Text> {this.renderRows(rowData)} </View> ); } renderRows(rowData: Array<Object>) { return rowData.map((cell) => { const {title, info} = cell; return ( <View key={title} style={styles.rowContainer}> <View style={styles.rowLabelContainer}> <Text style={styles.rowLabel}>{title}</Text> </View> <View style={styles.rowInfoContainer}> <Text style={styles.rowInfo}>{info}</Text> </View> </View> ); }); } render() { return ( <View style={styles.mainContainer}> <Image source={Images.background} style={styles.backgroundImage} resizeMode="stretch" /> <ScrollView style={styles.container}> <View style={styles.section}> <Text style={styles.sectionText} > Dedicated to identifying specifics of the device. All info useful for identifying outlying behaviour specific to a device. </Text> </View> {this.renderCard('Device Hardware', HARDWARE_DATA)} {this.renderCard('Device OS', OS_DATA)} {this.renderCard('App Info', APP_DATA)} {this.renderCard('Net Info', this.netInfo())} </ScrollView> </View> ); } }
src/components/Conversation/RequestItem.js
andresmechali/shareify
import React from 'react'; import PropTypes from 'prop-types'; import { withApollo } from 'react-apollo'; import classNames from 'classnames'; import REQUEST_ITEM from "../../utils/queries/REQUEST_ITEM"; class RequestItem extends React.Component { constructor(props) { super(props); this.state = { } } onRequestItem() { this.props.client.mutate({ query: REQUEST_ITEM, variables: { _id: this.props.user._id } }) .then(res => { const activityIdList = []; res.data.activityByUserIdMessage.forEach(act => {activityIdList.push(act._id)}); this.props.client.mutate({ mutation: VIEW_ACTIVITY, variables: { activityId: activityIdList, } }) }) .catch(activityErr => { console.log(activityErr) }); } render() { return ( <div className="ui-block"> <div className="ui-block-content"> <button className="btn btn-green btn-lg" onClick={this.onRequestItem.bind(this)}>Request item</button> </div> </div> ) } } MessageList.propTypes = { user: PropTypes.object.isRequired, conversation: PropTypes.object.isRequired, }; export default withApollo(MessageList);
admin/client/components/Forms/CreateForm.js
wmertens/keystone
import React from 'react'; import Fields from '../../fields'; import InvalidFieldType from './InvalidFieldType'; import { Alert, Button, Form, Modal } from 'elemental'; var CreateForm = React.createClass({ displayName: 'CreateForm', propTypes: { err: React.PropTypes.object, isOpen: React.PropTypes.bool, list: React.PropTypes.object, onCancel: React.PropTypes.func, onCreate: React.PropTypes.func, values: React.PropTypes.object, }, getDefaultProps () { return { err: null, values: {}, isOpen: false, }; }, getInitialState () { var values = Object.assign({}, this.props.values); Object.keys(this.props.list.fields).forEach(key => { var field = this.props.list.fields[key]; if (!values[field.path]) { values[field.path] = field.defaultValue; } }); return { values: values, err: this.props.err, }; }, componentDidMount () { if (this.refs.focusTarget) { this.refs.focusTarget.focus(); } }, componentDidUpdate (prevProps) { if (this.props.isOpen !== prevProps.isOpen) { // focus the focusTarget after the "open modal" CSS animation has started setTimeout(() => this.refs.focusTarget && this.refs.focusTarget.focus(), 0); } }, handleChange (event) { var values = Object.assign({}, this.state.values); values[event.path] = event.value; this.setState({ values: values, }); }, getFieldProps (field) { var props = Object.assign({}, field); props.value = this.state.values[field.path]; props.values = this.state.values; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, submitForm (event) { // If there is an onCreate function, // create new item using async create api instead // of using a POST request to the list endpoint. if (this.props.onCreate) { event.preventDefault(); const createForm = this.refs.createForm.getDOMNode(); const formData = new FormData(createForm); this.props.list.createItem(formData, (err, data) => { if (data) { this.props.onCreate(data); this.setState({ values: {}, err: null, }); // Clear form } else { this.setState({ err: err.detail, }); } }); } }, renderAlerts () { if (!this.state.err || !this.state.err.errors) return; const errors = this.state.err.errors; var alertContent; var errorCount = Object.keys(errors).length; var messages = Object.keys(errors).map((path) => { return errorCount > 1 ? <li key={path}>{errors[path].message}</li> : <div key={path}>{errors[path].message}</div>; }); if (errorCount > 1) { alertContent = ( <div> <h4>There were {errorCount} errors creating the new {this.props.list.singular}:</h4> <ul>{messages}</ul> </div> ); } else { alertContent = messages; } return <Alert type="danger">{alertContent}</Alert>; }, renderForm () { if (!this.props.isOpen) return; var form = []; var list = this.props.list; var formAction = `${Keystone.adminPath}/${list.path}`; var nameField = this.props.list.nameField; var focusRef; if (list.nameIsInitial) { var nameFieldProps = this.getFieldProps(nameField); nameFieldProps.ref = focusRef = 'focusTarget'; if (nameField.type === 'text') { nameFieldProps.className = 'item-name-field'; nameFieldProps.placeholder = nameField.label; nameFieldProps.label = false; } form.push(React.createElement(Fields[nameField.type], nameFieldProps)); } Object.keys(list.initialFields).forEach(key => { var field = list.fields[list.initialFields[key]]; if (typeof Fields[field.type] !== 'function') { form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } var fieldProps = this.getFieldProps(field); if (!focusRef) { fieldProps.ref = focusRef = 'focusTarget'; } form.push(React.createElement(Fields[field.type], fieldProps)); }); return ( <Form ref="createForm" type="horizontal" encType="multipart/form-data" method="post" action={formAction} onSubmit={this.submitForm} className="create-form"> <input type="hidden" name="action" value="create" /> <input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} /> <Modal.Header text={'Create a new ' + list.singular} onClose={this.props.onCancel} showCloseButton /> <Modal.Body> {this.renderAlerts()} {form} </Modal.Body> <Modal.Footer> <Button type="success" submit>Create</Button> <Button type="link-cancel" onClick={this.props.onCancel}>Cancel</Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal isOpen={this.props.isOpen} onCancel={this.props.onCancel} backdropClosesModal> {this.renderForm()} </Modal> ); }, }); module.exports = CreateForm;
withReduxSaga/withReduxSaga.js
batusai513/next-saga-boilerplate
import React, { Component } from 'react'; import withRedux from 'next-redux-wrapper'; export default params => (InnerComponent, actions) => { class ReduxContainer extends Component { static async getInitialProps({ store, isServer, ...rest }) { if (isServer) { const action = actions.server || actions; const rootTask = store.runSagas(); store.dispatch(Object.assign({}, action, { isServer }, { query: rest.query })); store.close(); await rootTask.done.then(() => store.reset()); } else { const action = actions.client || actions; store.runSagas(); store.dispatch(Object.assign({}, action, { isServer }, { query: rest.query })); } } constructor(props) { super(props); params.store.runSagas(); } render() { return <InnerComponent {...this.props} />; } } return withRedux(params.makeStore)(ReduxContainer); };
stories/sizeReport.js
quanxiaoxiao/size-report
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import SizeReport from '../src/main'; class Quan extends React.Component { state = { width: 0, height: 0, } handleChange({ width, height }) { this.setState({ width, height, }); } render() { const { width, height } = this.state; return ( <div> <p>width: {width}px, height: {height}px</p> <SizeReport onChange={::this.handleChange} style={{ resize: 'both', width: '100px', border: '1px solid black', overflow: 'scroll', }} > You can resize me! </SizeReport> </div> ); } } storiesOf('SizeReport', module) .add('default view', () => ( <Quan /> ));
tools/render.js
ahw/flash-cards-static-app
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import glob from 'glob'; import { join, dirname } from 'path'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from '../components/Html'; import task from './lib/task'; import fs from './lib/fs'; const DEBUG = !process.argv.includes('release'); const timestamp = Date.now() function getPages() { return new Promise((resolve, reject) => { glob('**/*.js', { cwd: join(__dirname, '../pages') }, (err, files) => { if (err) { reject(err); } else { const result = files.map(file => { let path = '/' + file.substr(0, file.lastIndexOf('.')); if (path === '/index') { path = '/'; } else if (path.endsWith('/index')) { path = path.substr(0, path.lastIndexOf('/index')); } return { path, file }; }); resolve(result); } }); }); } async function renderManifest() { let content = `CACHE MANIFEST # ${new Date(timestamp).toLocaleString()} 3p-libraries/fastclick.js 3p-libraries/inobounce.js tile.png https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=AM_CHTML https://cdn.mathjax.org/mathjax/2.7-latest/config/AM_CHTML.js?V=2.7.0 app.js?${timestamp} 1.app.js 2.app.js # The * indicates that the browser should allow all connections to non-cached # resources from a cached page. NETWORK: * ` content.split('\n').forEach((line) => { console.log(' ' + line); }); await fs.writeFile(join(__dirname, '../build/offline.appcache'), content); } async function renderPage(page, component) { const data = { body: ReactDOM.renderToString(component), timestamp }; const file = join(__dirname, '../build', page.file.substr(0, page.file.lastIndexOf('.')) + '.html'); const html = '<!doctype html>\n' + ReactDOM.renderToStaticMarkup(<Html debug={DEBUG} {...data} />); await fs.mkdir(dirname(file)); await fs.writeFile(file, html); } export default task(async function render() { const pages = await getPages(); const { route } = require('../build/app.node'); for (const page of pages) { await route(page.path, renderPage.bind(undefined, page)); } await renderManifest(); });
src/client/login.js
DBCDK/dbc-ufo
/** * @file * Client side login file. */ import ReactDOM from 'react-dom'; import React from 'react'; // Components import TopbarContainer from './components/topbar/topbarContainer.component'; import LoginContainer from './components/login/loginContainer.component'; const topbarContainer = document.getElementById('topbar'); const rootContainer = document.getElementById('content'); ReactDOM.render(<div><TopbarContainer /></div>, topbarContainer); ReactDOM.render(<div><LoginContainer /></div>, rootContainer);
test/integration/client-navigation/pages/async-props.js
zeit/next.js
import React from 'react' export default class AsyncProps extends React.Component { static async getInitialProps() { return fetchData() } render() { return <p>{this.props.name}</p> } } function fetchData() { const p = new Promise((resolve) => { setTimeout(() => resolve({ name: 'Diego Milito' }), 10) }) return p }
node_modules/react-router/es6/Router.js
MichaelWiss/React_E
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import createHashHistory from 'history/lib/createHashHistory'; import useQueries from 'history/lib/useQueries'; import invariant from 'invariant'; import React from 'react'; import createTransitionManager from './createTransitionManager'; import { routes } from './InternalPropTypes'; import RouterContext from './RouterContext'; import { createRoutes } from './RouteUtils'; import { createRouterObject, createRoutingHistory } from './RouterUtils'; import warning from './routerWarning'; function isDeprecatedHistory(history) { return !history || !history.__v2_compatible__; } /* istanbul ignore next: sanity check */ function isUnsupportedHistory(history) { // v3 histories expose getCurrentLocation, but aren't currently supported. return history && history.getCurrentLocation; } var _React$PropTypes = React.PropTypes; var func = _React$PropTypes.func; var object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = React.createClass({ displayName: 'Router', propTypes: { history: object, children: routes, routes: routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // Deprecated: parseQueryString: func, stringifyQuery: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return React.createElement(RouterContext, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount: function componentWillMount() { var _this = this; var _props = this.props; var parseQueryString = _props.parseQueryString; var stringifyQuery = _props.stringifyQuery; process.env.NODE_ENV !== 'production' ? warning(!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : void 0; var _createRouterObjects = this.createRouterObjects(); var history = _createRouterObjects.history; var transitionManager = _createRouterObjects.transitionManager; var router = _createRouterObjects.router; this._unlisten = transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { _this.setState(state, _this.props.onUpdate); } }); this.history = history; this.router = router; }, createRouterObjects: function createRouterObjects() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext; } var history = this.props.history; var _props2 = this.props; var routes = _props2.routes; var children = _props2.children; !!isUnsupportedHistory(history) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v3.x. ' + 'This version of React Router is not compatible with v3 history ' + 'objects. Please use history v2.x instead.') : invariant(false) : void 0; if (isDeprecatedHistory(history)) { history = this.wrapDeprecatedHistory(history); } var transitionManager = createTransitionManager(history, createRoutes(routes || children)); var router = createRouterObject(history, transitionManager); var routingHistory = createRoutingHistory(history, transitionManager); return { history: routingHistory, transitionManager: transitionManager, router: router }; }, wrapDeprecatedHistory: function wrapDeprecatedHistory(history) { var _props3 = this.props; var parseQueryString = _props3.parseQueryString; var stringifyQuery = _props3.stringifyQuery; var createHistory = void 0; if (history) { process.env.NODE_ENV !== 'production' ? warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : void 0; createHistory = function createHistory() { return history; }; } else { process.env.NODE_ENV !== 'production' ? warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : void 0; createHistory = createHashHistory; } return useQueries(createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state; var location = _state.location; var routes = _state.routes; var params = _state.params; var components = _state.components; var _props4 = this.props; var createElement = _props4.createElement; var render = _props4.render; var props = _objectWithoutProperties(_props4, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { history: this.history, router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); export default Router;
docs/app/Examples/modules/Dropdown/States/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const DropdownStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Loading' description='A dropdown can show that it is currently loading data.' examplePath='modules/Dropdown/States/DropdownExampleLoading' /> <ComponentExample title='Error' description='An errored dropdown can alert a user to a problem.' examplePath='modules/Dropdown/States/DropdownExampleError' /> <ComponentExample title='Active' description='An active dropdown has its menu open.' examplePath='modules/Dropdown/States/DropdownExampleActive' /> <ComponentExample title='Disabled' description='A disabled dropdown menu does not allow user interaction.' examplePath='modules/Dropdown/States/DropdownExampleDisabled' /> <ComponentExample description='A disabled dropdown item does not allow user interaction.' examplePath='modules/Dropdown/States/DropdownExampleDisabledItem' /> </ExampleSection> ) export default DropdownStatesExamples
src/components/Tabs/components/InkTabBarMixin.js
zhangjianguo1500/f01
import { setTransform, isTransformSupported } from './utils'; import React from 'react'; import classnames from 'classnames'; export function getScroll(w, top) { let ret = w[`page${top ? 'Y' : 'X'}Offset`]; const method = `scroll${top ? 'Top' : 'Left'}`; if (typeof ret !== 'number') { const d = w.document; // ie6,7,8 standard mode ret = d.documentElement[method]; if (typeof ret !== 'number') { // quirks mode ret = d.body[method]; } } return ret; } function offset(elem) { let box; let x; let y; const doc = elem.ownerDocument; const body = doc.body; const docElem = doc && doc.documentElement; box = elem.getBoundingClientRect(); x = box.left; y = box.top; x -= docElem.clientLeft || body.clientLeft || 0; y -= docElem.clientTop || body.clientTop || 0; const w = doc.defaultView || doc.parentWindow; x += getScroll(w); y += getScroll(w, true); return { left: x, top: y, }; } function componentDidUpdate(component, init) { const refs = component.refs; const wrapNode = refs.nav || refs.root; const containerOffset = offset(wrapNode); const inkBarNode = refs.inkBar; const activeTab = refs.activeTab; const inkBarNodeStyle = inkBarNode.style; const tabBarPosition = component.props.tabBarPosition; if (init) { // prevent mount animation inkBarNodeStyle.display = 'none'; } if (activeTab) { const tabNode = activeTab; const tabOffset = offset(tabNode); const transformSupported = isTransformSupported(inkBarNodeStyle); if (tabBarPosition === 'top' || tabBarPosition === 'bottom') { const left = tabOffset.left - containerOffset.left; // use 3d gpu to optimize render if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`); inkBarNodeStyle.width = `${tabNode.offsetWidth}px`; inkBarNodeStyle.height = ''; // setTimeout(function(){ // },500); } else { inkBarNodeStyle.left = `${left}px`; inkBarNodeStyle.top = ''; inkBarNodeStyle.bottom = ''; inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - tabNode.offsetWidth}px`; } } else { const top = tabOffset.top - containerOffset.top; if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`); inkBarNodeStyle.height = `${tabNode.offsetHeight}px`; inkBarNodeStyle.width = ''; } else { inkBarNodeStyle.left = ''; inkBarNodeStyle.right = ''; inkBarNodeStyle.top = `${top}px`; inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - tabNode.offsetHeight}px`; } } } inkBarNodeStyle.display = activeTab ? 'block' : 'none'; } export default { getDefaultProps() { return { inkBarAnimated: true, }; }, componentDidUpdate() { componentDidUpdate(this); }, componentDidMount() { componentDidUpdate(this, true); }, getInkBarNode() { const { prefixCls, styles, inkBarAnimated } = this.props; const className = `${prefixCls}-ink-bar`; const classes = classnames({ [className]: true, [ inkBarAnimated ? `${className}-animated` : `${className}-no-animated` ]: true, }); return ( <div style={styles.inkBar} className={classes} key="inkBar" ref="inkBar" /> ); }, };
src/Map/Layers/Marker.js
woutervh-/cancun-react
import React from 'react'; export default class Marker extends React.Component { static propTypes = { position: React.PropTypes.shape({ latitude: React.PropTypes.number.isRequired, longitude: React.PropTypes.number.isRequired }).isRequired, anchor: React.PropTypes.shape({ x: React.PropTypes.number.isRequired, y: React.PropTypes.number.isRequired }).isRequired, width: React.PropTypes.number.isRequired, height: React.PropTypes.number.isRequired, source: React.PropTypes.string.isRequired }; static defaultProps = { anchor: {x: 0, y: 0} }; render() { return null; } };
src/svg-icons/image/control-point.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageControlPoint = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ImageControlPoint = pure(ImageControlPoint); ImageControlPoint.displayName = 'ImageControlPoint'; ImageControlPoint.muiName = 'SvgIcon'; export default ImageControlPoint;
src/routes/home/index.js
RomanovRoman/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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 Home from './Home'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,contentSnippet}}', }), credentials: 'include', }); 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><Home news={data.news} /></Layout>, }; }, };
src/components/introduction/Introduction.js
DarylRodrigo/DarylRodrigo.github.io
import React from 'react'; import Scroll from '../common/Scroll'; import laptopCover from '../../images/laptopCover.png'; const Introduction = () => ( <section id="intro" className="wrapper style2 spotlights show-case"> <div className="inner"> <div className="content-section"> <div className="intro-nav"> <h2 className="navLink"> <a href="#work">Work</a> </h2> <h2 className="navLink"> <a href="#projects">Projects</a> </h2> <h2 className="navLink"> <a href="#about">About</a> </h2> </div> <div className="intro-content"> <h1 className="title"> Daryl Rodrigo</h1> <div className="break"></div> <h3 className="description"> {' '} Research Engineer - passionate about how <b>AI</b> can make a{' '} <b>positive</b> impact on the world.{' '} </h3> </div> <div className="intro-nav mobile-hide"></div> </div> <div className="content-section intro-image"> <center> <img className="cover-image" src={laptopCover} alt="" data-position="center center" /> </center> </div> </div> <ul className="icons social-links"> <li> <a href="https://twitter.com/DarylRodrigo" target="_blank" className="icon fa-twitter fa-2x" > <span className="label">Twitter</span> </a> </li> <li> <a href="https://github.com/DarylRodrigo" className="icon fa-github fa-2x" target="_blank" > <span className="label">GitHub</span> </a> </li> <li> <a href="https://linkedin.com/in/darylrodrigo" target="_blank" className="icon fa-linkedin fa-2x" > <span className="label">LinkedIn</span> </a> </li> </ul> </section> ); export default Introduction;
frontend/react-slingshot/src/components/NotFoundPage.js
ggchan0/git_diffed
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/svg-icons/notification/phone-locked.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhoneLocked = (props) => ( <SvgIcon {...props}> <path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM20 4v-.5C20 2.12 18.88 1 17.5 1S15 2.12 15 3.5V4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm-.8 0h-3.4v-.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V4z"/> </SvgIcon> ); NotificationPhoneLocked = pure(NotificationPhoneLocked); NotificationPhoneLocked.displayName = 'NotificationPhoneLocked'; NotificationPhoneLocked.muiName = 'SvgIcon'; export default NotificationPhoneLocked;
resource/js/components/HeaderSearchBox/SearchSuggest.js
crow-misia/crowi
import React from 'react'; import ListView from '../PageList/ListView'; export default class SearchSuggest extends React.Component { render() { if (!this.props.focused) { return <div></div>; } if (this.props.searching) { return ( <div className="search-suggest" id="search-suggest"> <i className="searcing fa fa-circle-o-notch fa-spin fa-fw"></i> Searching ... </div> ); } if (this.props.searchError !== null) { return ( <div className="search-suggest" id="search-suggest"> <i className="searcing fa fa-warning"></i> Error on searching. </div> ); } if (this.props.searchedPages.length < 1) { if (this.props.searchingKeyword !== '') { return ( <div className="search-suggest" id="search-suggest"> No results for "{this.props.searchingKeyword}". </div> ); } return <div></div>; } return ( <div className="search-suggest" id="search-suggest"> <ListView pages={this.props.searchedPages} /> </div> ); } } SearchSuggest.propTypes = { searchedPages: React.PropTypes.array.isRequired, searchingKeyword: React.PropTypes.string.isRequired, searching: React.PropTypes.bool.isRequired, }; SearchSuggest.defaultProps = { searchedPages: [], searchingKeyword: '', searchError: null, searching: false, focused: false, };
docs/app/Examples/elements/Label/Content/LabelExampleImage.js
koenvg/Semantic-UI-React
import React from 'react' import { Image, Label } from 'semantic-ui-react' const LabelExampleImage = () => ( <div> <Label as='a'> <Image avatar spaced='right' src='http://semantic-ui.com/images/avatar/small/elliot.jpg' /> Elliot </Label> <Label as='a'> <img src='http://semantic-ui.com/images/avatar/small/stevie.jpg' /> Stevie </Label> </div> ) export default LabelExampleImage
test/integration/image-component/default/pages/rotated.js
JeromeFitz/next.js
import Image from 'next/image' import React from 'react' const Page = () => { return ( <div> <p>Hello World</p> <Image id="exif-rotation-image" src="/exif-rotation.jpg" unsized /> <p id="stubtext">This is the rotated page</p> </div> ) } export default Page
js/pages/logframe/index.js
mercycorps/TolaActivity
/** * Entry point for the logframe webpack bundle */ import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'mobx-react'; import FilterStore from './models/filterStore'; import ProgramStore from './models/programStore'; import TitleBar from './components/title'; import LogframeApp from './components/main'; const filterStore = new FilterStore(); const dataStore = new ProgramStore(jsContext); ReactDOM.render( <Provider filterStore={ filterStore } dataStore={ dataStore }> <TitleBar /> </Provider>, document.querySelector('.region-header')); ReactDOM.render( <Provider filterStore={ filterStore } dataStore={ dataStore }> <LogframeApp /> </Provider>, document.querySelector('#id_div_content'));
src/components/errors/ErrorView.js
ZhukMax/feap
import React from 'react'; import { Link } from 'react-router'; import { Container, Row, Col } from 'reactstrap'; class ErrorView extends React.Component { render() { return ( <Container className="b-container"> <div className="b-content-wrapper"> <Container className="b-content"> <Row> <Col> <h3>Произошла ошибка.</h3><br/> <p>{ this.props.error }</p> <p>Вернуться на <Link to='/admin'>главную</Link></p> </Col> </Row> </Container> </div> </Container> ); }; } export default ErrorView;
app/components/Console/Console.js
crysislinux/chrome-react-perf
import React from 'react'; import Log from './Log'; import Table from './Table'; import styles from './Console.css'; const propTypes = { data: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.array, ]).isRequired, }; function renderData(data) { if (typeof data === 'string') { return <Log log={data} />; } return <Table tabular={data} />; } export default function Console({ data }) { return ( <div className={styles.console}> {renderData(data)} </div> ); } Console.propTypes = propTypes;
src/components/MediaListItem.js
ratedali/desudesu
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Card, { CardActions, CardContent, CardMedia } from 'material-ui/Card'; import { CircularProgress } from 'material-ui/Progress'; import IconButton from 'material-ui/IconButton'; import Button from 'material-ui/Button'; import Typography from 'material-ui/Typography'; import apiSpec from '../apiSpec'; const styles = theme => ({ card: { width: '240px', [theme.breakpoints.up('sm')]: { minHeight: '400px', }, [theme.breakpoints.up('md')]: { width: '320px', minHeight: '480px', } }, actions: { justifyContent: 'center', }, spacer: { flex: '1 1 auto', }, statusButton: { fontSize: theme.typography.subheading.fontSize, fontWeight: theme.typography.button.fontWeight }, progressContainer: { width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', } }); class MediaListItem extends Component { static propTypes = { mediaId: PropTypes.number.isRequired, mediaType: PropTypes.oneOf([ apiSpec.mediaType.anime, apiSpec.mediaType.manga ]).isRequired, isLoading: PropTypes.bool, error: PropTypes.string, media: PropTypes.object, progress: PropTypes.number, score: PropTypes.number, loadMedia: PropTypes.func.isRequired, }; componentDidMount() { this.props.loadMedia({ id: this.props.mediaId, mediaType: this.props.mediaType }); } render() { const { classes, mediaType, isLoading, media, progress, score, } = this.props; const { coverImage, title, [mediaType === apiSpec.mediaType.anime ? 'episodes' : 'chapters'] : total, } = media ? media : {}; return ( <Card className={classes.card}> { media ? <div> <CardMedia className={classes.cover} component="img" src={coverImage.large} title={title.english ? title.english : title.romaji}/> <CardContent> <Typography type="headline" component="h2" gutterBottom> {title.romaji} </Typography> </CardContent> <CardActions className={classes.actions}> <Button focusRipple className={classes.statusButton}> {progress}/{total ? total : '?'} </Button> <IconButton>add</IconButton> <div className={classes.spacer}/> <Button focusRipple color="primary" className={classes.statusButton}> {score} </Button> </CardActions> </div> : isLoading ? <div className={classes.progressContainer}> <CircularProgress className={classes.progress} size={160} color="accent"/> </div> : null } </Card> ); } } export default withStyles(styles)(MediaListItem);
Libraries/Components/TextInput/TextInput.js
naoufal/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNative = require('ReactNative'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const View = require('View'); const warning = require('fbjs/lib/warning'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const PropTypes = React.PropTypes; const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; type Selection = { start: number, end?: number, }; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * */ const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...View.propTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * Pressed key value is passed as an argument to the callback handler. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.node, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight (and cursor on iOS) color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.node, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * [Styles](/react-native/docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], viewConfig: ((Platform.OS === 'ios' && RCTTextField ? RCTTextField.viewConfig : (Platform.OS === 'android' && AndroidTextInput ? AndroidTextInput.viewConfig : {})) : Object), /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: React.PropTypes.func, focusEmitter: React.PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [styles.input, this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, }); var styles = StyleSheet.create({ input: { alignSelf: 'stretch', }, }); module.exports = TextInput;
project/src/scenes/Account/AccountContainer.js
boldr/boldr
/* @flow */ import React from 'react'; import Route from 'react-router-dom/Route'; import { flattenRoutes } from '@boldr/core'; import type { FlattenedRoutes } from '../../types/boldr'; import routes from './routes'; type Props = { path: string, }; // eslint-disable-next-line const AccountContainer = (props: Props) => { const flattenedRoutes: FlattenedRoutes = flattenRoutes(routes); return <div>{flattenedRoutes.map(props => <Route key={props.path} {...props} />)}</div>; }; export default AccountContainer;
src/containers/Link.js
cyrfer/firestarter
import React from 'react' import PropTypes from 'prop-types' const Link = ({ active, children, onClick }) => { if (active) { return <span>{children}</span> } return ( <a href="#" onClick={e => { e.preventDefault() onClick() }} > {children} </a> ) } Link.propTypes = { active: PropTypes.bool.isRequired, children: PropTypes.node.isRequired, onClick: PropTypes.func.isRequired } export default Link
src/js/main.js
caseypt/ebird-hotspot-viewer
import '../sass/app.scss'; import '../index.html'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; import Home from './components/Home.js'; import About from './components/About.js'; import HotspotList from './components/HotspotList.js'; import SightingsList from './components/SightingsList.js'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/hotspots" component={HotspotList} /> <Route path="/hotspot/:hotspotId" component={SightingsList} /> <Route path="/about" component={About} /> </Route> </Router> ), document.getElementById('app'));
src/client/components/pages/editor-revision.js
bookbrainz/bookbrainz-site
/* * Copyright (C) 2020 Prabal Singh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import PagerElement from './parts/pager'; import PropTypes from 'prop-types'; import React from 'react'; import RevisionsTable from './parts/revisions-table'; class EditorRevisionPage extends React.Component { constructor(props) { super(props); this.state = { results: this.props.results }; this.searchResultsCallback = this.searchResultsCallback.bind(this); this.paginationUrl = './revisions/revisions'; } searchResultsCallback(newResults) { this.setState({results: newResults}); } render() { return ( <div id="pageWithPagination"> <RevisionsTable results={this.state.results} showEntities={this.props.showEntities} showRevisionEditor={this.props.showRevisionEditor} showRevisionNote={this.props.showRevisionNote} tableHeading={this.props.tableHeading} /> <PagerElement from={this.props.from} nextEnabled={this.props.nextEnabled} paginationUrl={this.paginationUrl} results={this.state.results} searchResultsCallback={this.searchResultsCallback} size={this.props.size} /> </div> ); } } EditorRevisionPage.displayName = 'EditorRevisionPage'; EditorRevisionPage.propTypes = { from: PropTypes.number, nextEnabled: PropTypes.bool.isRequired, results: PropTypes.array, showEntities: PropTypes.bool, showRevisionEditor: PropTypes.bool, showRevisionNote: PropTypes.bool, size: PropTypes.number, tableHeading: PropTypes.string }; EditorRevisionPage.defaultProps = { from: 0, results: [], showEntities: true, showRevisionEditor: false, showRevisionNote: true, size: 20, tableHeading: 'Recent Activity' }; export default EditorRevisionPage;
src/svg-icons/image/lens.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLens = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/> </SvgIcon> ); ImageLens = pure(ImageLens); ImageLens.displayName = 'ImageLens'; export default ImageLens;
resources/assets/js/common/components/TimeAgo.js
vestd/ProcessMonitor
import React from 'react'; import {FormattedRelative, injectIntl} from 'react-intl'; const TimeAgo = ({date, intl}) => { if (date == null) { return (<span>-</span>) } return ( <FormattedRelative value={new Date(date)} /> ) } //Inject the internationalisation data into the component export default injectIntl(TimeAgo)
node_modules/react-router/es6/Route.js
fahidRM/aqua-couch-test
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Route;