path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
client/src/CompConfig/CompConfig.js
Nichsiciul/User-Friendly-CMS
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Col, Form, FormControl, FormGroup, ControlLabel, Glyphicon, Button, Panel } from 'react-bootstrap'; import axios from 'axios'; import { SliderPicker } from 'react-color'; import ColorBullet from './../ColorBullet/ColorBullet.js'; import './CompConfig.css'; class CompConfig extends Component { constructor(...args) { super(...args); this.state = { open: false }; } changesMade = () => { var changes = { title: ReactDOM.findDOMNode(this.refs.title).value, content: ReactDOM.findDOMNode(this.refs.content).value, hasLine: ReactDOM.findDOMNode(this.refs.line).checked, }; this.props.componentChanged(changes); }; submitChanges = (event) => { event.preventDefault(); axios.put('/api/components', this.props).then((data) => { console.log(data.data); }); }; deleteComponent = () => { axios.delete('/api/components', {params: { id: this.props.unique }}).then((data) => { console.log(data.data); }); }; render() { return ( <div className="position-relative"> <Button className="edit-button" bsStyle="info" onClick={() => this.setState({ open: !this.state.open })}> <Glyphicon glyph="edit" /> </Button> <Button className="delete-button" bsStyle="danger" onClick={this.deleteComponent}> <Glyphicon glyph="trash" /> </Button> <Panel collapsible className="color-black" expanded={this.state.open} header="Component Configurations" bsStyle="primary"> <Form horizontal onSubmit={this.submitChanges}> <FormGroup> <Col componentClass={ControlLabel} sm={2}> Title </Col> <Col sm={10}> <FormControl type="text" value={this.props.title} ref="title" onChange={this.changesMade} /> </Col> </FormGroup> <FormGroup> <Col componentClass={ControlLabel} sm={2}> Content </Col> <Col sm={10}> <FormControl componentClass="textarea" value={this.props.content} ref="content" onChange={this.changesMade} /> </Col> </FormGroup> <FormGroup> <Col componentClass={ControlLabel} sm={2}> Show Line </Col> <Col sm={10}> <div className="checkbox-wrap"> <input type="checkbox" checked={this.props.hasLine} ref="line" onChange={this.changesMade} /> </div> </Col> </FormGroup> <FormGroup> <Col smOffset={2} sm={10}> <Button type="submit" bsStyle="primary" > Save Changes </Button> </Col> </FormGroup> </Form> </Panel> </div> ) } } export default CompConfig;
src/svg-icons/av/av-timer.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAvTimer = (props) => ( <SvgIcon {...props}> <path d="M11 17c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1zm0-14v4h2V5.08c3.39.49 6 3.39 6 6.92 0 3.87-3.13 7-7 7s-7-3.13-7-7c0-1.68.59-3.22 1.58-4.42L12 13l1.41-1.41-6.8-6.8v.02C4.42 6.45 3 9.05 3 12c0 4.97 4.02 9 9 9 4.97 0 9-4.03 9-9s-4.03-9-9-9h-1zm7 9c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zM6 12c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1z"/> </SvgIcon> ); AvAvTimer = pure(AvAvTimer); AvAvTimer.displayName = 'AvAvTimer'; AvAvTimer.muiName = 'SvgIcon'; export default AvAvTimer;
app/javascript/mastodon/components/load_more.js
ikuradon/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class LoadMore extends React.PureComponent { static propTypes = { onClick: PropTypes.func, disabled: PropTypes.bool, visible: PropTypes.bool, } static defaultProps = { visible: true, } render() { const { disabled, visible } = this.props; return ( <button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}> <FormattedMessage id='status.load_more' defaultMessage='Load more' /> </button> ); } }
stories/examples/AlertContent.js
reactstrap/reactstrap
import React from 'react'; import { Alert } from 'reactstrap'; const Example = (props) => { return ( <div> <Alert color="success"> <h4 className="alert-heading">Well done!</h4> <p> Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content. </p> <hr /> <p className="mb-0"> Whenever you need to, be sure to use margin utilities to keep things nice and tidy. </p> </Alert> </div> ); }; export default Example;
src/containers/Home/Home.js
yomolify/customer-webserver
import React, { Component } from 'react'; import { Link } from 'react-router'; import { CounterButton, GithubButton } from 'components'; import AppointmentViewer from '../../components/AppointmentViewer/AppointmentViewer'; import PractitionerAvatar from '../../components/AppointmentViewer/PractitionerComponents/PractitionerAvatar'; import SearchBar from '../../components/SearchBar/SearchBar'; import Sticky from "react-sticky"; import SimpleMapPage from '../../components/Map/SimpleMapPage' const styles = require('./Home.scss'); console.log('styles', styles); export default class Home extends Component { render() { // require the logo image both from client and server const logoImage = require('../../../static/cclogo_big.png'); return ( <div className={styles.home}> <div className={styles.masthead}> <div className="container"> <div className={styles.logo}> <p> <img src={logoImage}/> </p> </div> </div> <div style={{width:"42%", backgroundColor:"#B2EBF2"}}> <div style={{width:"100%", padding:"10px", float:"center"}}> <AppointmentViewer /> </div> </div> </div> </div> ); } } // export default class Home extends Component { // render() { // const styles = require('./Home.scss'); // // require the logo image both from client and server // const logoImage = require('../../../static/cclogo_big.png'); // return ( // <div> // <div> // <div> // <div className={styles.logo}> // <p> // <img src={logoImage}/> // </p> // </div> // <div style = {{ // position: "absolute", // right:"0px", // top: "60px", // width: "100%", // height: "40px", // zIndex: "2", // background:"white"}}> // <SearchBar/> // </div> // <div style={{backgroundColor:"#0097A7", width:"40%"}}> // <AppointmentViewer /> // </div> // <div id="map" style={{width:"60%"}}> // <SimpleMapPage/> // </div> // </div> // </div> // </div> // ); // } // }
egghead.io/react_fundamentals/lessons/14-build-compiler/main.js
andrisazens/learning_react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
client/routes.js
Gin-And-Tomic/tune-stream
/* eslint-disable global-require */ import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './modules/App/App'; // require.ensure polyfill for node if (typeof require.ensure !== 'function') { require.ensure = function requireModule(deps, callback) { callback(require); }; } /* Workaround for async react routes to work with react-hot-reloader till https://github.com/reactjs/react-router/issues/2182 and https://github.com/gaearon/react-hot-loader/issues/288 is fixed. */ if (process.env.NODE_ENV !== 'production') { // Require async routes only in development for react-hot-reloader to work. } // react-router setup with code-splitting // More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/ export default ( <Route path="/" component={App}> <IndexRoute getComponent={(nextState, cb) => { require.ensure([], require => { cb(null, require('./modules/Song/pages/SongListPage').default); }); }} /> <Route path="/songs/:id" getComponent={(nextState, cb) => { require.ensure([], require => { cb(null, require('./modules/Song/pages/SongDetailPage').default); }); }} /> </Route> );
src/propTypes/StyleSheetPropType.js
RealOrangeOne/react-native-mock
/** * https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/StyleSheetPropType.js */ import React from 'react'; import flattenStyle from './flattenStyle'; const { PropTypes } = React; function StyleSheetPropType(shape) { const shapePropType = PropTypes.shape(shape); return function (props, propName, componentName, ...rest) { let newProps = props; if (props[propName]) { // Just make a dummy prop object with only the flattened style newProps = {}; newProps[propName] = flattenStyle(props[propName]); } return shapePropType(newProps, propName, componentName, ...rest); }; } module.exports = StyleSheetPropType;
src/server.js
th3hunt/observatory
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import http from 'http'; import io from 'socket.io'; import Poller from './core/poller'; const app = global.server = express(); const port = (process.env.PORT || 5000); app.set('port', port); app.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server with WebSocket support on the same port // ----------------------------------------------------------------------------- const server = http.Server(app); server.listen(port, () => { if (process.send) { process.send('online'); } }); const webSocketConnection = io.listen(server); const poller = new Poller(webSocketConnection); webSocketConnection.on('connect', () =>{ poller.tap(); }); poller.execute();
examples/real-world/routes.js
conorhastings/redux
import React from 'react' import { Route } from 'react-router' import App from './containers/App' import UserPage from './containers/UserPage' import RepoPage from './containers/RepoPage' export default ( <Route path="/" component={App}> <Route path="/:login/:name" component={RepoPage} /> <Route path="/:login" component={UserPage} /> </Route> )
docs/src/app/components/pages/components/Slider/ExampleSimple.js
owencm/material-ui
import React from 'react'; import Slider from 'material-ui/Slider'; /** * The `defaultValue` property sets the initial position of the slider. The slider * appearance changes when not at the starting position. */ const SliderExampleSimple = () => ( <div> <Slider /> <Slider defaultValue={0.5} /> <Slider defaultValue={1} /> </div> ); export default SliderExampleSimple;
src/components/sensor_temp.js
asommer70/mirror-pila
import React, { Component } from 'react'; import axios from 'axios'; export default class SensorTemp extends Component { constructor(props) { super(props); this.state = { outsideTemp: null, humidity: null, insideTemp: null } axios.get('/api/outside') .then((res) => { this.setState({outsideTemp: res.data.temp, humidity: res.data.humidity}) }) .catch(function (error) { console.log('GET /api/outside error:', error); }); axios.get('/data/inside_temp.json') .then((res) => { this.setState({insideTemp: res.data.temp}); }) .catch(function (error) { console.log('GET inside_temp.json error:', error); }); } render() { return ( <div> <div className="row"> <div className="col-12"> <h2>Outside Temp: <span id="outside-temp">{this.state.outsideTemp}</span>&deg;</h2> <p>Humidity: <span id="outside-humidity">{this.state.humidity}</span>%</p> </div> </div> <div className="row"> <div className="col-12"> <h2>Inside Temp: <span id="inside-temp">{this.state.insideTemp}</span>&deg;</h2> </div> </div> </div> ) } }
app/containers/NotFoundPage/index.js
maxxafari/draftjs-comment-text
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a 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 NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/components/todo_group.js
dragonman225/TODO-React
import React from 'react'; import TodoGroupItem from './todo_group_item'; import TodoAddGroup from './todo_add_group'; const todoGroup = (props) => { const empty = (props.groups.length === 0); const error = (props.showErrMsg); const todoGroupItems = props.groups.map((item) => { return ( <TodoGroupItem onItemSelect={props.onItemSelect} onItemRemove={props.onItemRemove} onEditGroupChange={props.onEditGroupChange} onGroupNameChange={props.onGroupNameChange} name={item.name} id={item.id} key={item.id} editting={item.id === props.edittingGroupId} newGroupName={props.newGroupName} /> ); }); return ( <div className="group-pane"> <table> <tbody> {empty ? <tr><td className="td-empty" /><td className="td-center">No TODOs</td></tr> : todoGroupItems} </tbody> </table> {error ? <div className="msg-err"><i className="fa fa-exclamation-triangle" aria-hidden="true" />WARNING: Field is empty or Name exists!</div> : <div />} <TodoAddGroup addGroup={props.addGroup} adding={props.edittingGroupId !== null} /> </div> ); }; export default todoGroup;
electron/app/containers/EditorLeftPanel.js
zindlerb/static
import React from 'react'; import { connect } from 'react-redux'; import FormLabel from '../components/forms/FormLabel'; import TextField from '../components/forms/TextField'; import ComponentTreeContainer from '../components/ComponentTreeContainer'; import HorizontalSelect from '../components/HorizontalSelect'; import { createImmutableJSSelector } from '../utils'; import { renderTreeSelector } from '../selectors'; const panelTypes = { TREE: 'TREE', DETAILS: 'DETAILS' }; const EditorLeftPanel = React.createClass({ getInitialState() { return { activePanel: panelTypes.TREE } }, render() { const { actions, renderTree, currentPage, activeComponentId, hoveredComponentId } = this.props; const { activePanel } = this.state; let body; if (!currentPage) { return <h2 className="suggestion">No Page Selected</h2>; } if (activePanel === panelTypes.DETAILS) { const inputs = [ { name: 'name', key: 'metaName' }, { name: 'url', key: 'url' }, { name: 'author', key: 'author' }, { name: 'title', key: 'title' }, { name: 'description', key: 'description', large: true }, { name: 'keywords', key: 'keywords', large: true }, ].map((input) => { return ( <FormLabel name={input.name}> <TextField key={input.key} value={currentPage.get(input.key)} onSubmit={(value) => { this.props.actions.setPageValue(input.key, value); }} isLarge={input.large} /> </FormLabel> ); }); body = ( <div> { inputs } </div> ); } else if (activePanel === panelTypes.TREE) { body = ( <ComponentTreeContainer actions={actions} renderTree={renderTree} activeComponentId={activeComponentId} hoveredComponentId={hoveredComponentId} /> ); } return ( <div className="h-100 flex flex-column"> <HorizontalSelect className="w-100" options={[ { value: panelTypes.TREE, text: 'Tree' }, { value: panelTypes.DETAILS, text: 'Page Settings' }, ]} activePanel={this.state.activePanel} onClick={(value) => { this.setState({ activePanel: value }); }} /> <div className="f-grow"> {body} </div> </div> ); } }); const editorLeftPanelSelector = createImmutableJSSelector( [ renderTreeSelector, state => state.getIn(['pages', state.getIn(['editorView', 'currentPageId'])]), state => state.get('activeComponentId'), state => state.get('hoveredComponentId'), ], (renderTree, currentPage, activeComponentId, hoveredComponentId) => { return { renderTree, currentPage, activeComponentId, hoveredComponentId }; } ); export default connect(editorLeftPanelSelector)(EditorLeftPanel);
packages/veritone-widgets/src/widgets/EngineSelection/story.js
veritone/veritone-sdk
import React from 'react'; import { noop } from 'lodash'; import { storiesOf } from '@storybook/react'; import BaseStory from '../../shared/BaseStory'; import { EngineSelectionWidget } from './'; storiesOf('EngineSelectionWidget', module) .add('Base', () => { const props = { onSave: noop, onCancel: noop }; return <BaseStory widget={EngineSelectionWidget} widgetProps={props} />; }) .add('With initial selected engines', () => { const props = { onSave: noop, onCancel: noop, initialSelectedEngineIds: ['20bdf75f-add6-4f91-9661-fe50fb73b526'] }; return <BaseStory widget={EngineSelectionWidget} widgetProps={props} />; }) .add('With all engines selected by default (opt out)', () => { const props = { onSave: noop, onCancel: noop, allEnginesSelected: true }; return <BaseStory widget={EngineSelectionWidget} widgetProps={props} />; }) .add('With initial deselected engines (opt out)', () => { const props = { onSave: noop, onCancel: noop, allEnginesSelected: true, initialDeselectedEngineIds: ['20bdf75f-add6-4f91-9661-fe50fb73b526'] }; return <BaseStory widget={EngineSelectionWidget} widgetProps={props} />; });
app/javascript/mastodon/containers/status_container.js
riku6460/chikuwagoddon
import React from 'react'; import { connect } from 'react-redux'; import Status from '../components/status'; import { makeGetStatus } from '../selectors'; import { replyCompose, mentionCompose, directCompose, } from '../actions/compose'; import { reblog, favourite, unreblog, unfavourite, pin, unpin, } from '../actions/interactions'; import { blockAccount } from '../actions/accounts'; import { muteStatus, unmuteStatus, deleteStatus, hideStatus, revealStatus, } from '../actions/statuses'; import { initMuteModal } from '../actions/mutes'; import { initReport } from '../actions/reports'; import { openModal } from '../actions/modal'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { boostModal, deleteModal } from '../initial_state'; import { showAlertForError } from '../actions/alerts'; const messages = defineMessages({ deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' }, redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' }, redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' }, blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' }, replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' }, replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' }, }); const makeMapStateToProps = () => { const getStatus = makeGetStatus(); const mapStateToProps = (state, props) => ({ status: getStatus(state, props), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onReply (status, router) { dispatch((_, getState) => { let state = getState(); if (state.getIn(['compose', 'text']).trim().length !== 0) { dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.replyMessage), confirm: intl.formatMessage(messages.replyConfirm), onConfirm: () => dispatch(replyCompose(status, router)), })); } else { dispatch(replyCompose(status, router)); } }); }, onModalReblog (status) { dispatch(reblog(status)); }, onReblog (status, e) { if (status.get('reblogged')) { dispatch(unreblog(status)); } else { if (e.shiftKey || !boostModal) { this.onModalReblog(status); } else { dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog })); } } }, onFavourite (status) { if (status.get('favourited')) { dispatch(unfavourite(status)); } else { dispatch(favourite(status)); } }, onPin (status) { if (status.get('pinned')) { dispatch(unpin(status)); } else { dispatch(pin(status)); } }, onEmbed (status) { dispatch(openModal('EMBED', { url: status.get('url'), onError: error => dispatch(showAlertForError(error)), })); }, onDelete (status, history, withRedraft = false) { if (!deleteModal) { dispatch(deleteStatus(status.get('id'), history, withRedraft)); } else { dispatch(openModal('CONFIRM', { message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage), confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm), onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)), })); } }, onDirect (account, router) { dispatch(directCompose(account, router)); }, onMention (account, router) { dispatch(mentionCompose(account, router)); }, onOpenMedia (media, index) { dispatch(openModal('MEDIA', { media, index })); }, onOpenVideo (media, time) { dispatch(openModal('VIDEO', { media, time })); }, onBlock (account) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.blockConfirm), onConfirm: () => dispatch(blockAccount(account.get('id'))), })); }, onReport (status) { dispatch(initReport(status.get('account'), status)); }, onMute (account) { dispatch(initMuteModal(account)); }, onMuteConversation (status) { if (status.get('muted')) { dispatch(unmuteStatus(status.get('id'))); } else { dispatch(muteStatus(status.get('id'))); } }, onToggleHidden (status) { if (status.get('hidden')) { dispatch(revealStatus(status.get('id'))); } else { dispatch(hideStatus(status.get('id'))); } }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
src/components/LatexMath.js
donjar/learn-latex
import React from 'react'; import { InlineMath, BlockMath } from 'react-katex'; class LatexMath extends React.Component { render() { if (this.props.display === "inline") { return (<InlineMath math={this.props.math} />); } else if (this.props.display === "block") { return (<BlockMath math={this.props.math} />); } } } export default LatexMath;
src/index.js
juandjara/ftunes-client
import React from 'react'; import ReactDOM from 'react-dom'; import Root from './Root'; ReactDOM.render( <Root />, document.getElementById('root') );
cheesecakes/plugins/content-manager/admin/src/components/VariableEditIcon/index.js
strapi/strapi-examples
/** * * VariableEditIcon */ import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import styles from './styles.scss'; function VariableEditIcon({ onClick, withLongerHeight, ...rest }) { return ( <span className={cn(withLongerHeight ? styles.editIconLonger : styles.editIcon)} onClick={onClick} {...rest} /> ); } VariableEditIcon.defaultProps = { onClick: () => {}, withLongerHeight: false, }; VariableEditIcon.propTypes = { onClick: PropTypes.func, withLongerHeight: PropTypes.bool, }; export default VariableEditIcon;
static/js/login.js
wolendranh/movie_radio
import React from 'react'; import {auth} from './auth.jsx'; module.exports = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, handleSubmit: function(e) { e.preventDefault(); var username = this.refs.username.value; var pass = this.refs.pass.value; auth.login(username, pass, (loggedIn) => { if (loggedIn) { this.context.router.replace('/app/') } }) }, render: function() { return ( <form onSubmit={this.handleSubmit}> <input type="text" placeholder="username" ref="username" /> <input type="password" placeholder="password" ref="pass" /> <input type="submit" /> </form> ) } });
web/src/index.js
impl21/budget-ui
import "../../modules/uikit/less/uikit.less" import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import configureStore from './store' import routes from './routes' import './index.less'; let store = configureStore(); ReactDOM.render(( <Provider store={store}> {routes(store)} </Provider> ), document.getElementById('app'));
packages/ringcentral-widgets-docs/src/app/pages/Styles/Buttons/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import classnames from 'classnames'; import PrimaryButtonSpecs from '../../../assets/images/primary_button_specs.svg'; import PrimaryButtonPopupSpecs from '../../../assets/images/primary_button_popup_specs.svg'; import primaryButtonPageExample from '../../../assets/images/primary_button_in_page_example.png'; import primaryButtonPopupExample from '../../../assets/images/primary_button_in_popup_example.png'; import styles from './styles.scss'; function ButtonsWrapper(props) { const style = { width: `${props.width}px`, height: `${props.height}px`, lineHeight: `${props.height}px`, borderRadius: `${props.cornerRadius}px`, color: props.textColor, fontSize: `${props.textSize}px`, }; const buttons = ['normal', 'hover', 'pressed', 'disable'].map((type) => { let buttonStyle = { ...style }; if (props[`${type}Style`]) { buttonStyle = { ...style, ...(props[`${type}Style`]) }; } return ( <div key={type} className={styles.button} style={buttonStyle} > {type.charAt(0).toUpperCase() + type.slice(1)} </div> ); }); const fillDesriptions = ['normal', 'hover', 'pressed', 'disable'].map((type) => { const typeStyle = props[`${type}Style`]; const name = type.charAt(0).toUpperCase() + type.slice(1); return ( <div key={type}> <div className={styles.descriptionLine} key={type}> {name} fill color: {typeStyle.backgroundName} {typeStyle.background} </div> { typeStyle.borderColorName && ( <div className={styles.descriptionLine}> {name} border color: {typeStyle.borderColorName} </div> ) } { typeStyle.colorName && ( <div className={styles.descriptionLine}> {name} Text: {props.textSize} {typeStyle.colorName} {typeStyle.color} </div> ) } </div> ); }); return ( <div className={styles.buttonsWrapperRoot}> <div className={styles.wrapperTitle}>{props.title}</div> <div className={styles.wrapperButtonList}> {buttons} </div> <div className={styles.description}> <div className={styles.descriptionLine}> Minumum width: {props.width} </div> <div className={styles.descriptionLine}> Height: {props.height} </div> <div className={styles.descriptionLine}> Corner radius: {props.cornerRadius} </div> { props.textColor && ( <div className={styles.descriptionLine}> Text: {props.textSize} {props.textColorName} {props.textColor} </div> ) } { fillDesriptions } </div> </div> ); } const primaryButtonInPage = { title: 'Primary button in the page', width: 260, height: 35, cornerRadius: 100, textSize: 13, textColor: '#FFFFFF', textColorName: 'Regular Snow', normalStyle: { background: '#0684BD', backgroundName: 'RC Blue' }, hoverStyle: { background: '#389DCA', backgroundName: 'Sea' }, pressedStyle: { background: '#0570A1', backgroundName: 'Marine' }, disableStyle: { background: '#C7C7C7', backgroundName: 'Smoke' } }; const secondaryButtonInPage = { title: 'Secondary button in the page', width: 260, height: 35, cornerRadius: 100, textSize: 13, normalStyle: { background: 'transparent', color: '#0684BD', border: 'solid 1px rgba(6, 132, 189, 0.5)', borderColorName: '50% RC Blue #0684BD' }, hoverStyle: { color: '#FFFFFF', background: '#389DCA', backgroundName: 'Sea' }, pressedStyle: { color: '#FFFFFF', background: '#0570A1', backgroundName: 'Marine' }, disableStyle: { background: '#FFFFFF', backgroundName: 'Snow', color: '#C7C7C7', colorName: 'Smoke', border: 'solid 1px #C7C7C7', borderColorName: '50% Smoke #C7C7C7' } }; const primaryButtonInPopup = { title: 'Primary button in the popup', width: 70, height: 28, cornerRadius: 100, textSize: 12, textColor: '#FFFFFF', textColorName: 'Regular Snow', normalStyle: { background: '#0684BD', backgroundName: 'RC Blue' }, hoverStyle: { background: '#389DCA', backgroundName: 'Sea' }, pressedStyle: { background: '#0570A1', backgroundName: 'Marine' }, disableStyle: { background: '#C7C7C7', backgroundName: 'Smoke' } }; const secondaryButtonInPopup = { title: 'Secondary button in the popup', width: 70, height: 28, cornerRadius: 100, textSize: 12, normalStyle: { background: 'transparent', color: '#0684BD', colorName: 'RC Blue', border: 'solid 1px rgba(6, 132, 189, 0.5)', borderColorName: '50% RC Blue #0684BD' }, hoverStyle: { color: '#FFFFFF', background: '#389DCA', backgroundName: 'Sea' }, pressedStyle: { color: '#FFFFFF', background: '#0570A1', backgroundName: 'Marine' }, disableStyle: { background: '#FFFFFF', backgroundName: 'Snow', color: '#C7C7C7', colorName: 'Smoke', border: 'solid 1px #C7C7C7' } }; function ButtonsPage() { return ( <div className={styles.root}> <div className={styles.header}> Button </div> <div className={styles.subHeader}>Size & Specs</div> <div className={styles.buttonListGroup}> <div className={styles.buttonList}> <ButtonsWrapper {...primaryButtonInPage} /> </div> <div className={styles.buttonList}> <ButtonsWrapper {...secondaryButtonInPage} /> </div> </div> <div className={styles.clearLine} /> <div className={classnames(styles.buttonListGroup, styles.exampleGroup)}> <div className={styles.buttonList}> <div className={classnames(styles.button, styles.buttonExample)} style={{ width: 260, height: 35, lineHeight: '35px', }} > Normal </div> </div> <div className={styles.buttonList}> <PrimaryButtonSpecs width="100%" /> </div> </div> <div className={styles.clearLine} /> <div className={styles.buttonListGroup}> <img src={primaryButtonPageExample} alt="primary button in page examples" width="100%" /> </div> <div className={styles.clearLine} /> <div className={styles.buttonListGroup}> <div className={styles.buttonList}> <ButtonsWrapper {...primaryButtonInPopup} /> </div> <div className={styles.buttonList}> <ButtonsWrapper {...secondaryButtonInPopup} /> </div> </div> <div className={styles.clearLine} /> <div className={classnames(styles.buttonListGroup, styles.exampleGroup)}> <div className={styles.buttonList}> <div className={classnames(styles.button, styles.buttonExample)} style={{ width: 68, height: 28, fontSize: '12px', lineHeight: '28px', }} > Normal </div> </div> <div className={styles.buttonList}> <PrimaryButtonPopupSpecs width="100%" /> </div> </div> <div className={styles.clearLine} /> <div className={styles.buttonListGroup}> <img src={primaryButtonPopupExample} alt="primary button in popup examples" width="100%" /> </div> </div> ); } export default ButtonsPage;
src/svg-icons/hardware/keyboard-arrow-down.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowDown = (props) => ( <SvgIcon {...props}> <path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z"/> </SvgIcon> ); HardwareKeyboardArrowDown = pure(HardwareKeyboardArrowDown); HardwareKeyboardArrowDown.displayName = 'HardwareKeyboardArrowDown'; HardwareKeyboardArrowDown.muiName = 'SvgIcon'; export default HardwareKeyboardArrowDown;
app/index.js
CaseyLeask/starting-again
import React from 'react'; export default (props) => <p>Hello World</p>;
src/Header.js
dmed256/website
import React from 'react'; import { Button, Toolbar, Typography, withStyles, } from 'material-ui'; import { getHistory } from './utils'; const MenuButton = ({ name, path }) => ( <Button color="inherit" onClick={() => { getHistory().push(path); }} > {name} </Button> ); const Header = ({ classes }) => ( <Toolbar classes={{ root: classes.toolbar, }} > <Typography type="title" color="inherit" classes={{ root: classes.title, }} > David Medina </Typography> <MenuButton name="Home" path="/home" /> <MenuButton name="About" path="/about" /> <MenuButton name="Projects" path="/projects" /> <MenuButton name="Contact" path="/contact" /> </Toolbar> ); export default withStyles({ toolbar: { width: 'calc(100% - 40px)', margin: 'auto', padding: 0, }, title: { flex: 1, color: '#969696', fontWeight: 300, textTransform: 'uppercase', } })(Header);
src/components/Footer/index.js
devrsi0n/React-2048-game
import React from 'react'; import PropTypes from 'prop-types'; import styles from './footer.scss'; import github from '../../assets/images/github.png'; // Footer, link to github repo and developer profile export default class Footer extends React.Component { static propTypes = { name: PropTypes.string.isRequired, repoUrl: PropTypes.string.isRequired, profileUrl: PropTypes.string.isRequired }; // Render once, no update shouldComponentUpdate() { return false; } render() { const { props: { name, repoUrl, profileUrl } } = this; return ( <div className={styles.footer}> <div className={styles.container}> <div> <a href={repoUrl} className={styles.icon}> <img src={github} className={styles.github} alt="github repo" /> </a> </div> Build with <span className={styles.heart}>♥</span> by <a href={profileUrl} className={styles.link}> {name} </a> </div> </div> ); } }
react/exercises/part_05/src/index.js
jsperts/workshop_unterlagen
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import './index.css'; import AppContainer from './containers/App'; import { getContacts } from './actions'; import store from './store'; store.dispatch(getContacts()); const root = ( <Provider store={store}> <AppContainer /> </Provider> ); ReactDOM.render(root, document.getElementById('root'));
examples/async/index.js
andreieftimie/redux
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
frontend/src/AlbumStudio/AlbumStudioConnector.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { clearAlbums, fetchAlbums } from 'Store/Actions/albumActions'; import { saveAlbumStudio, setAlbumStudioFilter, setAlbumStudioSort } from 'Store/Actions/albumStudioActions'; import createArtistClientSideCollectionItemsSelector from 'Store/Selectors/createArtistClientSideCollectionItemsSelector'; import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector'; import AlbumStudio from './AlbumStudio'; function createAlbumFetchStateSelector() { return createSelector( (state) => state.albums.items.length, (state) => state.albums.isFetching, (state) => state.albums.isPopulated, (length, isFetching, isPopulated) => { const albumCount = (!isFetching && isPopulated) ? length : 0; return { albumCount, isFetching, isPopulated }; } ); } function createMapStateToProps() { return createSelector( createAlbumFetchStateSelector(), createArtistClientSideCollectionItemsSelector('albumStudio'), createDimensionsSelector(), (albums, artist, dimensionsState) => { const isPopulated = albums.isPopulated && artist.isPopulated; const isFetching = artist.isFetching || albums.isFetching; return { ...artist, isPopulated, isFetching, albumCount: albums.albumCount, isSmallScreen: dimensionsState.isSmallScreen }; } ); } const mapDispatchToProps = { fetchAlbums, clearAlbums, setAlbumStudioSort, setAlbumStudioFilter, saveAlbumStudio }; class AlbumStudioConnector extends Component { // // Lifecycle componentDidMount() { this.populate(); } componentWillUnmount() { this.unpopulate(); } // // Control populate = () => { this.props.fetchAlbums(); } unpopulate = () => { this.props.clearAlbums(); } // // Listeners onSortPress = (sortKey) => { this.props.setAlbumStudioSort({ sortKey }); } onFilterSelect = (selectedFilterKey) => { this.props.setAlbumStudioFilter({ selectedFilterKey }); } onUpdateSelectedPress = (payload) => { this.props.saveAlbumStudio(payload); } // // Render render() { return ( <AlbumStudio {...this.props} onSortPress={this.onSortPress} onFilterSelect={this.onFilterSelect} onUpdateSelectedPress={this.onUpdateSelectedPress} /> ); } } AlbumStudioConnector.propTypes = { setAlbumStudioSort: PropTypes.func.isRequired, setAlbumStudioFilter: PropTypes.func.isRequired, fetchAlbums: PropTypes.func.isRequired, clearAlbums: PropTypes.func.isRequired, saveAlbumStudio: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(AlbumStudioConnector);
docs/src/index.js
Temzasse/react-buffet
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.scss'; ReactDOM.render( <App />, document.getElementById('root'), );
app/src/containers/MentorshipContainer/index.js
udacityalumni/udacity-alumni-fe
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as MentorshipActionCreators from './actions'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet-udacity/components/Heading'; import Hero from 'grommet-udacity/components/Hero'; import Headline from 'grommet-udacity/components/Headline'; import { MartinRulz } from 'components'; const MentorshipPageImage = 'https://github.com/RyanCCollins/cdn/blob/master/alumni-webapp/mentoring.jpg?raw=true'; class Mentorship extends Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className={styles.mentorship}> <Hero backgroundImage={MentorshipPageImage} > <Headline strong> Udacity Mentorship </Headline> <Heading tag="h2" strong> Together, we are stronger </Heading> </Hero> <MartinRulz /> </div> ); } } // mapStateToProps :: {State} -> {Props} const mapStateToProps = (state) => ({ // myProp: state.myProp, }); // mapDispatchToProps :: Dispatch -> {Action} const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators( MentorshipActionCreators, dispatch ), }); const Container = cssModules(Mentorship, styles); export default connect( mapStateToProps, mapDispatchToProps )(Container);
examples/counter/index.js
edge/redux
import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import Counter from './components/Counter' import counter from './reducers' const store = createStore(counter) const rootEl = document.getElementById('root') function render() { ReactDOM.render( <Counter value={store.getState()} onIncrement={() => store.dispatch({ type: 'INCREMENT' })} onDecrement={() => store.dispatch({ type: 'DECREMENT' })} />, rootEl ) } render() store.subscribe(render)
index.android.js
DreamCloudWalker/SoccerMap
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import DiscoveryPage from './js/discovery/discovery' AppRegistry.registerComponent('RNFirst', () => DiscoveryPage);
src/React/Widgets/ProxyEditorWidget/example/index.js
Kitware/paraviewweb
import 'normalize.css'; import React from 'react'; import ReactDOM from 'react-dom'; import ProxyEditorWidget from 'paraviewweb/src/React/Widgets/ProxyEditorWidget'; import source from 'paraviewweb/src/React/Widgets/ProxyEditorWidget/example/source-proxy.json'; import representation from 'paraviewweb/src/React/Widgets/ProxyEditorWidget/example/representation-proxy.json'; import view from 'paraviewweb/src/React/Widgets/ProxyEditorWidget/example/view-proxy.json'; // -------------------------------------------------------------------------- // Main proxy editor widget example // -------------------------------------------------------------------------- const container = document.querySelector('.content'); const sections = [ Object.assign({ name: 'source', collapsed: false }, source), Object.assign({ name: 'representation', collapsed: true }, representation), Object.assign({ name: 'view', collapsed: true }, view), ]; ReactDOM.render( React.createElement(ProxyEditorWidget, { sections }), container ); document.body.style.margin = '10px';
packages/icons/src/md/av/FeaturedVideo.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdFeaturedVideo(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M42 6c2.2 0 4 1.8 4 4v28c0 2.2-1.8 4-4 4H6c-2.2 0-4-1.8-4-4V10c0-2.2 1.8-4 4-4h36zM24 24V10H6v14h18z" /> </IconBase> ); } export default MdFeaturedVideo;
blueocean-material-icons/src/js/components/svg-icons/hardware/devices-other.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareDevicesOther = (props) => ( <SvgIcon {...props}> <path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"/> </SvgIcon> ); HardwareDevicesOther.displayName = 'HardwareDevicesOther'; HardwareDevicesOther.muiName = 'SvgIcon'; export default HardwareDevicesOther;
assets/jsx/views/services/components/consulting.js
Tjorriemorrie/besetfree
import React from 'react' import classNames from 'classnames' import ServiceBox from './serviceBox' class Consulting extends React.Component { constructor(props) { super(props); this.state = { cons: [ { img: '/static/img/con_individual.jpg', title: 'Individual Consultation', duration: '1 hr', price: 'R500.00 pp', description: 'Individualized Care Programs, Consultations & Examination sessions are available. Clients receive a health screening to determine their current health status before recommending specific treatments and health coaching protocols.', expanded: false, }, { img: '/static/img/con_skype.jpg', title: '1on1 Online Consultation', duration: '30 min', price: 'R250.00 pp', description: 'International clients can make use of this unique feature. Also convenient for clients who has already received screening and who needs advice or follow up.', expanded: false, }, { img: '/static/img/con_family.jpg', title: 'Family/Couple/Group Consulting', duration: '1 hr', price: 'R400.00 pp', description: 'Family, group or couple packages include discounted rates. R300 per person (Health screening, nutritional and lifestyle coaching included-Medicines/supplements or any additional therapies excluded).Please contact me for additional info or terms of service.', expanded: false, }, { img: '/static/img/con_weight.jpg', title: 'Sustainable Weight Management', duration: '1 hr', price: 'R500.00 pp', description: 'Claim the true you! The client receives an individualized food/supplement program aimed at healing and boosting vitality. Detox and cleansing of the gut as well as closely monitoring fat/muscle/water percentage gives reliable indicators of results.', expanded: false, }, { img: '/static/img/con_stress.jpg', title: 'Stress Management techniques', duration: '1 hr', price: 'R350.00 pp', description: 'Learn to live free. Participants complete a stress measuring questionnaire followed by a presentation and information session regarding stress, stress statistics and management. We finish up with a practical stress reduction technique. Duration 1 hour', expanded: false, }, { img: '/static/img/con_recipe.jpg', title: 'Recipes & Daily Health Tips', duration: '1 hr', price: 'Free', description: 'Join the Facebook group to receive daily healthy recipe posts, wellness tips, or news. Keep in touch with like minded individuals who support each other and value their health.', expanded: false, }, { img: '/static/img/con_smoking.jpg', title: 'Stop Smoking Support', duration: '1 hr', price: 'R500.00 pp', description: 'Find the root cause of your smoking habit and make a change. Four sessions of R500 are required as a package. Those on a string budget can join the group Stop smoking program for a reduced rate.', expanded: false, } ] }; } render() { console.info('[Consulting] render'); return <div className="wrapper"> <div className="services_grid"> {this.state.cons.map((con, i) => { return <ServiceBox key={'con_' + i} info={con} i={i} toggle={() => this.toggleExpanded(i)} />; })} </div> </div>; } toggleExpanded(i) { console.info('[Consulting] toggleExpanded', i); let { cons } = this.state; cons[i]['expanded'] = !cons[i]['expanded']; this.setState({cons: cons}); } } export default Consulting
src/scripts/app.js
IronNation/NCI-trial-search
import React from 'react' import ReactDOM from 'react-dom' import Backbone from 'backbone' import HomeView from './views/HomeView' import LoginView from './views/LoginView' import SearchView from './views/SearchView' import SearchResultsView from './views/SearchResultsView' import TrialDetailsView from './views/TrialDetailsView' import MyTrialsView from './views/MyTrialsView' import {TrialModel, TrialCollection} from './models/trialModel' const app = function() { const AppRouter = Backbone.Router.extend({ routes: { 'home': '_goHome', 'login': '_goToLogin', 'search': '_goToSearch', 'searchResults/:cancer': '_doSearch', 'trialDetails/:id' : '_goToTrialDetails', 'myTrials': '_goToMyTrials', '*default': '_goToDefault' }, _goHome: function() { ReactDOM.render(<HomeView />, document.querySelector('.container')) }, _goToLogin: function() { ReactDOM.render(<LoginView />, document.querySelector('.container')) }, _goToSearch: function() { const trialColl = new TrialCollection() trialColl.fetch().then(() => { ReactDOM.render(<SearchView trialColl = {trialColl}/>, document.querySelector('.container')) }) }, _doSearch: function(cancer) { const searchTrialColl = new TrialCollection() searchTrialColl.fetch({ data: { // eligibility.structured.gender: gender, _fulltext: cancer } }).then(() => { ReactDOM.render(<SearchResultsView searchTrialColl = {searchTrialColl}/>, document.querySelector('.container')) }) }, _goToTrialDetails: function(id) { const trialModel = new TrialModel(id) trialModel.fetch().then(() => { ReactDOM.render(<TrialDetailsView trialModel = {trialModel}/>, document.querySelector('.container')) }) }, _goToMyTrials: function() { ReactDOM.render(<MyTrialsView />, document.querySelector('.container')) }, _goToDefault: function() { location.hash = 'home' }, initialize: function() { Backbone.history.start() } }) new AppRouter() } app()
src/svg-icons/social/person-outline.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPersonOutline = (props) => ( <SvgIcon {...props}> <path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/> </SvgIcon> ); SocialPersonOutline = pure(SocialPersonOutline); SocialPersonOutline.displayName = 'SocialPersonOutline'; SocialPersonOutline.muiName = 'SvgIcon'; export default SocialPersonOutline;
website/src/components/common/InternalLink/index.js
jwngr/notreda.me
import React from 'react'; import {connect} from 'react-redux'; import {push} from 'connected-react-router'; function asInternalLink(WrappedComponent) { return class extends React.Component { handleClick(e) { const {href, onClick, navigateTo} = this.props; // Run the custom onClick method, if provided. onClick && onClick(); // Navigate to the new route. navigateTo(href); // Scroll back to the top of the page. window.scrollTo(0, 0); // Preven the default link behavior, which is a page reload. e.preventDefault(); } render() { const {navigateTo, onClick, ...otherProps} = this.props; return <WrappedComponent onClick={this.handleClick.bind(this)} {...otherProps} />; } }; } const mapDispatchToProps = (dispatch) => ({ navigateTo: (path) => { dispatch(push(path)); }, }); export default connect(null, mapDispatchToProps)(asInternalLink('a'));
src/website/app/demos/Select/Select/examples/portal.js
mineral-ui/mineral-ui
/* @flow */ import React, { Component } from 'react'; import { pxToEm } from '../../../../../../library/styles'; import ScrollParent from '../../../Popover/common/ScrollBox'; import _Select from '../../../../../../library/Select'; import { basicData as data } from '../../common/selectData'; type Props = any; // Not a functional component because ScrollParent throws a ref on it class Select extends Component<Props> { render() { return ( <div style={{ width: pxToEm(224) }}> <_Select {...this.props} /> </div> ); } } export default { id: 'portal', title: 'Portal', description: `Use a portal to render the Select to the body of the page rather than as a sibling of the trigger. This can be useful to visually "break out" of a bounding container with \`overflow\` or \`z-index\` styles. Note that you may have to adjust the \`modifiers\` to get the exact behavior that you want.`, scope: { data, ScrollParent, Select }, source: ` <ScrollParent> <Select data={data} usePortal isOpen modifiers={{ preventOverflow: { escapeWithReference: true } }} /> </ScrollParent>` };
src/client/auth/index.react.js
gaurav-/este
import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import Login from './login.react'; import React from 'react'; export default class Index extends Component { static propTypes = { msg: React.PropTypes.object.isRequired }; render() { const {msg} = this.props; return ( <DocumentTitle title={msg.auth.index.title}> <div className="login-page"> <Login {...this.props} /> </div> </DocumentTitle> ); } }
packages/core/tocco-ui/src/Button/RouterLinkButton.js
tocco/tocco-client
import PropTypes from 'prop-types' import React from 'react' import Icon from '../Icon' import {design} from '../utilStyles' import StyledRouterLinkButton from './StyledRouterLinkButton' const RouterLinkButton = React.forwardRef((props, ref) => { const {aria, icon, ink, label, iconOnly, children} = props return ( <StyledRouterLinkButton ref={ref} {...aria} {...props} ink={ink || design.ink.BASE} data-cy={props['data-cy']} title={label} > {icon && <Icon icon={icon} />} {!iconOnly && label ? <span>{label}</span> : children || '\u200B'} </StyledRouterLinkButton> ) }) RouterLinkButton.propTypes = { /** * A flat object of ARIA keys and values. */ aria: PropTypes.object, /** * Instead of using label prop it is possible to pass a child * (e.g. <LinkButton><FormattedMessage id="client.message"/></LinkButton>). This is not useful for * styled tags since buttons design is controlled by props ink and look and immutable. */ children: PropTypes.node, /** * If true, button occupies less space. It should only used for crowded areas like tables and only if necessary. */ dense: PropTypes.bool, /** * Display an icon alongside button label. It is possible to omit label text if an icon is chosen. * See Icon component for more information. */ icon: PropTypes.string, /** * Prepend icon or append icon to label. Default value is 'prepend'. * Possible values: append|prepend */ iconPosition: PropTypes.oneOf([design.position.APPEND, design.position.PREPEND]), /** * Specify color palette. Default value is 'base'. */ ink: design.inkPropTypes, /** * Describe button action concise. Default is ''. */ label: PropTypes.node, /** * Look of button. Default value is 'flat'. */ look: PropTypes.oneOf([design.look.BALL, design.look.FLAT, design.look.RAISED]), /** * Describe button action in detail to instruct users. It is shown as popover on mouse over. */ title: PropTypes.string, /** * Tabindex indicates if the button can be focused and if/where it participates * in sequential keyboard navigation. */ tabIndex: PropTypes.number, /** * cypress selector string */ 'data-cy': PropTypes.string, /** * If true, leaves the background of the button transparent and does not add any hove effect. */ withoutBackground: PropTypes.bool, /** * If true, renders only the icon and minimal space around it */ iconOnly: PropTypes.bool } export default RouterLinkButton
client/src/components/instructor/InstructorStudentsList.js
yegor-sytnyk/contoso-express
import React from 'react'; import InstructorStudentRow from './InstructorStudentRow'; const InstructorStudentsList = ({enrollments, visible}) => { let style = visible ? {display: 'block'} : {display: 'none'}; return ( <div style={style}> <h3>Students Enrolled in Selected Course</h3> <table className="table"> <thead> <tr> <th>Name</th> <th>Grade</th> </tr> </thead> <tbody> {enrollments.map(enrollment => <InstructorStudentRow key={enrollment.id} enrollment={enrollment} /> )} </tbody> </table> </div> ); }; InstructorStudentsList.propTypes = { visible: React.PropTypes.bool.isRequired, enrollments: React.PropTypes.array.isRequired }; export default InstructorStudentsList;
src/svg-icons/communication/phonelink-erase.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhonelinkErase = (props) => ( <SvgIcon {...props}> <path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z"/> </SvgIcon> ); CommunicationPhonelinkErase = pure(CommunicationPhonelinkErase); CommunicationPhonelinkErase.displayName = 'CommunicationPhonelinkErase'; CommunicationPhonelinkErase.muiName = 'SvgIcon'; export default CommunicationPhonelinkErase;
docs/app/Examples/collections/Form/Types/index.js
jcarbo/stardust
import React from 'react' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import { Message, Icon } from 'src' const FormTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Form' description='A form.' examplePath='collections/Form/Types/FormFormExample' > <Message info icon> <Icon name='pointing right' /> <Message.Content> Forms also have a robust shorthand props API for generating controls wrapped in FormFields. See shorthand examples below. </Message.Content> </Message> </ComponentExample> <ComponentExample title='onSubmit' description='A form calls back with the serialized data on submit' examplePath='collections/Form/Types/FormOnSubmitExample' /> </ExampleSection> ) export default FormTypesExamples
src/TabbedArea.js
erictherobot/react-bootstrap
import React from 'react'; import Tabs from './Tabs'; import TabPane from './TabPane'; import ValidComponentChildren from './utils/ValidComponentChildren'; import deprecationWarning from './utils/deprecationWarning'; const TabbedArea = React.createClass({ componentWillMount() { deprecationWarning( 'TabbedArea', 'Tabs', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { const {children, ...props} = this.props; const tabs = ValidComponentChildren.map(children, function (child) { const {tab: title, ...others} = child.props; return <TabPane title={title} {...others} />; }); return ( <Tabs {...props}>{tabs}</Tabs> ); } }); export default TabbedArea;
src/components/App.js
mm-taigarevolution/tas_web_app
/* eslint-disable import/no-named-as-default */ import React from 'react'; import { Route } from 'react-router-dom'; import { AnimatedSwitch } from 'react-router-transition'; import AuctionsPage from './pages/AuctionsPage'; import AuctionDetailsPage from './pages/AuctionDetailsPage'; import AuthenticationPage from './pages/AuthenticationPage'; import AuctionBidPage from './pages/AuctionBidPage'; import NotFoundPage from './pages/NotFoundPage'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. // we need to map the `scale` prop we define below // to the transform style property function mapStyles(styles) { return { opacity: styles.opacity }; } // child matches will... const opacityTransition = { // start in a transparent, upscaled state atEnter: { opacity: 0 }, // leave in a transparent, downscaled state atLeave: { opacity: 0 }, // and rest at an opaque, normally-scaled state atActive: { opacity: 1 }, }; class App extends React.Component { render() { return ( <AnimatedSwitch atEnter={opacityTransition.atEnter} atLeave={opacityTransition.atLeave} atActive={opacityTransition.atActive} mapStyles={mapStyles} className="route-wrapper"> <Route exact path="/" component={AuctionsPage} /> <Route exact path="/bid" component={AuctionBidPage} /> <Route exact path="/authenticate" component={AuthenticationPage} /> <Route exact path="/:id" component={AuctionDetailsPage} /> <Route component={NotFoundPage} /> </AnimatedSwitch> ); } } export default App;
test/helpers/shallowRenderHelper.js
xiaolin00/gallery-by-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
packages/maps/examples/mongo-examples/GeoDistanceDropdown/src/index.js
appbaseio/reactivesearch
import React from 'react'; import ReactDOM from 'react-dom'; import { ReactiveBase } from '@appbaseio/reactivesearch'; import { GeoDistanceDropdown, ReactiveGoogleMap, ReactiveOpenStreetMap, } from '@appbaseio/reactivemaps'; import Dropdown from '@appbaseio/reactivesearch/lib/components/shared/Dropdown'; const providers = [ { label: 'Google Map', value: 'googleMap', }, { label: 'OpenStreet Map', value: 'openstreetMap', }, ]; class App extends React.Component { constructor() { super(); this.state = { mapProvider: providers[0], }; this.setProvider = this.setProvider.bind(this); } setProvider(mapProvider) { this.setState({ mapProvider, }); } render() { const mapProps = { dataField: 'address.location', defaultMapStyle: 'Light Monochrome', title: 'Reactive Maps', defaultZoom: 13, index: 'custom', size: 100, react: { and: 'GeoDistanceDropdown', }, onPopoverClick: item => ( <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-start', }} > <div style={{ margin: '3px 0', height: '100px', width: '100%' }}> <img style={{ margin: '3px 0', height: '100%', width: '100%' }} src={item.images.picture_url} alt={item.name} /> </div> <div style={{ margin: '3px 0' }}> <b>Name: </b> {item.name} </div> <div style={{ margin: '3px 0' }}> <b>Room Type: </b> {item.room_type} </div> <div style={{ margin: '3px 0' }}> <b>Property Type: </b> {item.property_type} </div> </div> ), showMapStyles: true, renderItem: () => ({ custom: ( <div style={{ background: 'dodgerblue', color: '#fff', paddingLeft: 5, paddingRight: 5, borderRadius: 3, padding: 10, }} > <i className="fa fa-home" /> </div> ), }), }; return ( <ReactiveBase app="custom" url="https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/public-demo-skxjb/service/http_endpoint/incoming_webhook/reactivesearch" mongodb={{ db: 'sample_airbnb', collection: 'listingsAndReviews', }} enableAppbase mapKey="AIzaSyA9JzjtHeXg_C_hh_GdTBdLxREWdj3nsOU" mapLibraries={['places']} > <div> <h3 style={{ textAlign: 'center' }}>Search properties across the globe</h3> <div style={{ position: 'relative', zIndex: 9999999999, marginBottom: '2rem', }} > <GeoDistanceDropdown title="Filter by location" componentId="GeoDistanceDropdown" placeholder="Search Location" dataField="address.location" unit="mi" URLParams data={[ { distance: 10, label: 'Within 10 miles' }, { distance: 50, label: 'Within 50 miles' }, { distance: 100, label: 'Under 100 miles' }, { distance: 300, label: 'Under 300 miles' }, ]} defaultValue={{ location: 'Rio De Janeiro', label: 'Under 300 miles', }} /> </div> <div style={{ position: 'relative', zIndex: 2147483646, }} > <div> <b>Select Map Provider</b> </div> <Dropdown className="dropdown" items={providers} onChange={this.setProvider} selectedItem={this.state.mapProvider} keyField="label" returnsObject /> </div> {this.state.mapProvider.value === 'googleMap' ? ( <ReactiveGoogleMap style={{ height: '90vh', marginTop: '5px', padding: '1rem' }} componentId="googleMap" {...mapProps} /> ) : ( <ReactiveOpenStreetMap style={{ height: '90vh', marginTop: '5px', padding: '1rem' }} componentId="openstreetMap" {...mapProps} /> )} </div> </ReactiveBase> ); } } ReactDOM.render(<App />, document.getElementById('root'));
src/work/components/ProjectCardItem.js
elailai94/elailai94.github.io
import React, { Component } from 'react'; import { Card, Image, } from 'semantic-ui-react'; import PropTypes from 'prop-types'; import ProjectCardHeading from './ProjectCardHeading'; import ProjectCardLabels from './ProjectCardLabels'; import ProjectCardDescription from './ProjectCardDescription'; import ProjectCardLinks from './ProjectCardLinks'; class ProjectCardItem extends Component { render() { const { name } = this.props.project; const { technologies } = this.props.project; const { description } = this.props.project; const { links } = this.props.project; const { src } = this.props.project.image; const { alt } = this.props.project.image; return ( <Card raised> <Image src={src} alt={alt} /> <Card.Content> <ProjectCardHeading text={name} /> <ProjectCardLabels labels={technologies} /> <ProjectCardDescription text={description} /> </Card.Content> <Card.Content extra> <ProjectCardLinks links={links} /> </Card.Content> </Card> ); } } ProjectCardItem.propTypes = { project: PropTypes.object.isRequired, } export default ProjectCardItem;
packages/cf-component-form/src/FormFieldError.js
mdno/mdno.github.io
import React from 'react'; import PropTypes from 'prop-types'; import { createComponent } from 'cf-style-container'; const styles = ({ theme }) => ({ position: theme.position, marginTop: theme.marginTop, padding: theme.padding, border: theme.border, fontSize: theme.fontSize, fontWeight: theme.fontWeight, background: theme.background, color: theme.color, borderRadius: theme.borderRadius, boxShadow: theme.boxShadow, '-webkit-font-smoothing': 'antialiased', '&::before': { content: '""', display: 'block', position: 'absolute', bottom: '100%', borderStyle: 'solid', borderColor: 'transparent', left: '4px', borderWidth: '6px', borderBottomColor: theme.colorRed }, '&::after': { content: '""', display: 'block', position: 'absolute', bottom: '100%', borderStyle: 'solid', borderColor: 'transparent', left: '4px', borderWidth: '4px', borderBottomColor: theme.colorRed }, '& p': { marginTop: 0, marginBottom: 0 }, '& p + p': { marginTop: '0.5em' } }); class FormFieldError extends React.Component { render() { const { field, validations, className } = this.props; if (!field.invalid) { return null; } return ( <div className={className}> {Object.keys(validations).map(validation => { return ( <p key={validation}> {validations[validation]} </p> ); })} </div> ); } } FormFieldError.propTypes = { field: PropTypes.object.isRequired, validations: PropTypes.object.isRequired, className: PropTypes.string }; export default createComponent(styles, FormFieldError);
web/components/screens/onboarding/ZeroSum/index.fixture.js
skidding/flatris
// @flow import React from 'react'; import ZeroSum from '.'; export default <ZeroSum onNext={() => console.log('Next')} />;
src/components/Item.js
erikdesjardins/media-db
import React from 'react'; import ItemListCharacters from './ItemListCharacters'; import ItemListCreator from './ItemListCreator'; import ItemListGenres from './ItemListGenres'; import ItemListLength from './ItemListLength'; import ItemListNotes from './ItemListNotes'; import ItemListProductionStatus from './ItemListProductionStatus'; import ItemListStatusDate from './ItemListStatusDate'; import ItemListThumbnail from './ItemListThumbnail'; import ItemListTitle from './ItemListTitle'; export default React.memo(function Item({ item, onClickItem }) { const handleClick = () => { onClickItem(item); }; return ( <tr className="Item" onClick={handleClick}> <td><ItemListThumbnail item={item}/></td> <td><ItemListTitle item={item}/></td> <td><ItemListCreator item={item}/></td> <td><ItemListGenres item={item}/></td> <td><ItemListCharacters item={item}/></td> <td><ItemListNotes item={item}/></td> <td><ItemListStatusDate item={item}/></td> <td><ItemListLength item={item}/></td> <td><ItemListProductionStatus item={item}/></td> </tr> ); });
frontend/src/javascripts/stores/TokenStore.js
maru-3/notee
import React from 'react'; import assign from 'object-assign'; import request from 'superagent'; var EventEmitter = require('events').EventEmitter; // notee import NoteeDispatcher from '../dispatcher/NoteeDispatcher'; import Constants from '../constants/NoteeConstants'; // utils import EventUtil from '../utils/EventUtil'; var TokenStore = assign({}, EventEmitter.prototype, {}); function token_delete(){ request .del("/notee/tokens/1") .end(function(err, res){ if(err || !res.body){ EventUtil.emitChange(Constants.TOKEN_DELETE_FAILED); return false; } EventUtil.emitChange(Constants.TOKEN_DELETE); location.reload(); }) } NoteeDispatcher.register(function(action) { switch(action.type) { case Constants.TOKEN_DELETE: token_delete(); break; } }); module.exports = TokenStore;
crowdpact/static/js/apps/landing/components/LandingApp.js
joshmarlow/crowdpact
import React from 'react'; import LandingBanner from './LandingBanner'; import LandingHeader from './LandingHeader'; import LandingPacts from './LandingPacts'; import LandingStore from '../stores/LandingStore'; class LandingApp extends React.Component { constructor(...args) { super(...args); this.state = {data: LandingStore.data}; } componentWillMount() { this.unregister = LandingStore.listen(this.onStoreChange.bind(this)); } componentWillUnmount() { this.unregister(); } render() { return ( <div className="landing-app"> <LandingHeader {...this.props} {...this.state} /> <LandingBanner {...this.props} {...this.state} /> <LandingPacts {...this.props} {...this.state} /> </div> ); } onStoreChange() { this.setState({data: LandingStore.data}); } } export default LandingApp;
src/components/editor/editor.js
HendrikCrause/crossword-creator
import React from 'react' import { Table, TableBody, TableHeader } from 'material-ui/Table' import Row from './row' import ButtonRow from './buttonrow' import HeaderRow from './headerrow' import { narrowStyle, wordStyle, colStyle, actionsStyle } from './styles' import crosswordStore from '../../store/crosswordstore' import * as Actions from '../../actions/crosswordactions' const MIN_ROWS = 5 class Editor extends React.Component { constructor(props) { super(props) this.state = { words: crosswordStore.getAllWords() } this.resetWords = this.resetWords.bind(this) } resetWords() { this.setState({ words: crosswordStore.getAllWords() }) } componentWillMount() { crosswordStore.on('change', this.resetWords) } componentWillUnmount() { crosswordStore.removeListener('change', this.resetWords) } addWord() { Actions.addWord() } removeWord(number) { Actions.removeWord(number) } updateWord(word) { Actions.updateWord(word) } clearWords() { Actions.clearWords() } render() { return ( <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <HeaderRow/> </TableHeader> <TableBody displayRowCheckbox={false}> { this.state.words.map((w) => { return ( <Row key={w.number} number={w.number} word={w.word} clue={w.clue} handleRemoveWord={this.removeWord.bind(this)} handleUpdateWord={this.updateWord.bind(this)} /> ) }) } <ButtonRow handleAddWord={this.addWord.bind(this)} handleClearWords={this.clearWords.bind(this)} /> </TableBody> </Table> ) } } export default Editor
src/components/common/svg-icons/notification/airline-seat-recline-normal.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineNormal = (props) => ( <SvgIcon {...props}> <path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/> </SvgIcon> ); NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal); NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal'; NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineNormal;
views/Business/nwdAccount.js
leechuanjun/TLRNProjectTemplate
/** * Created by Bruce on Mon Jan 25 2016 23:28:33 GMT+0800 (CST). */ 'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, ScrollView, TouchableOpacity, } from 'react-native'; export default class NWDAccount extends Component { render(){ return ( <View style={styles.tabContent}> <TouchableOpacity onPress={this._navigateToSubview}> <View style={styles.button}><Text style={styles.buttonText}>Account content</Text></View> </TouchableOpacity> </View> ); } }; var styles = StyleSheet.create({ navigator: { flex: 1, }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, tabContent: { flex: 1, alignItems: 'center', justifyContent: 'center', }, });
hello world/1.6 - style/src/components/header.js
wumouren/react-demo
import React from 'react'; export default class Header extends React.Component { // state 演示 constructor(){ super() // 初始化 state 状态 let names = ['jack','tom','lili']; this.state = {name: names} } list(){ // 重新组装格式 let nameArr = []; this.state.name.map(function(item){ nameArr.push( <h3 key={item}>{item}</h3> ) }) this.setState({ nameList: nameArr }) } componentWillMount(){ // render 之前调用组装方法,重新组装数据 this.list(); } render() { let userName = 'jack'; return ( <div> <h1>这里是头部</h1> <div> <h2> state 中数据渲染 :</h2> {this.state.nameList} </div> <h1>这里是通过数据双向绑定,从 binding 文件中传来的值:{this.props.bindVal.str} : {this.props.bindVal.val}</h1> <hr/> </div> ) } }
client/containers/AppContainer.js
chenfanggm/steven-react-starter-kit
import '../styles/main.scss' import React from 'react' import { BrowserRouter } from 'react-router-dom' class AppContainer extends React.Component { render() { const { routes } = this.props; return (<BrowserRouter children={routes} />) } } export default AppContainer
app/addons/documents/changes/components/ChangeRow.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import PropTypes from 'prop-types'; import React from 'react'; import { v4 as uuidv4 } from 'uuid'; import FauxtonAPI from '../../../../core/api'; import Components from '../../../fauxton/components'; import ReactComponents from '../../../components/react-components'; import ChangesCodeTransition from './ChangesCodeTransition'; import ChangeID from './ChangeID'; const {Copy} = ReactComponents; export default class ChangeRow extends React.Component { constructor (props) { super(props); this.state = { codeVisible: false }; } toggleJSON (e) { e.preventDefault(); this.setState({ codeVisible: !this.state.codeVisible }); } getChangesCode () { return (this.state.codeVisible) ? <Components.CodeFormat key="changesCodeSection" code={this.getChangeCode()} /> : null; } getChangeCode () { return { changes: this.props.change.changes, doc: this.props.change.doc }; } showCopiedMessage (target) { let msg = 'The document ID has been copied to your clipboard.'; if (target === 'seq') { msg = 'The document seq number has been copied to your clipboard.'; } FauxtonAPI.addNotification({ msg: msg, type: 'info', clear: true }); } render () { const { codeVisible } = this.state; const { change, databaseName } = this.props; const wrapperClass = 'change-wrapper' + (change.isNew ? ' new-change-row' : ''); return ( <div className={wrapperClass}> <div className="change-box" data-id={change.id}> <div className="row-fluid"> <div className="span2">seq</div> <div className="span8 change-sequence">{change.seq}</div> <div className="span2 text-right"> <Copy uniqueKey={uuidv4()} text={change.seq.toString()} onClipboardClick={() => this.showCopiedMessage('seq')} /> </div> </div> <div className="row-fluid"> <div className="span2">id</div> <div className="span8"> <ChangeID id={change.id} deleted={change.deleted} databaseName={databaseName} /> </div> <div className="span2 text-right"> <Copy uniqueKey={uuidv4()} text={change.id} onClipboardClick={() => this.showCopiedMessage('id')} /> </div> </div> <div className="row-fluid"> <div className="span2">deleted</div> <div className="span10">{change.deleted ? 'True' : 'False'}</div> </div> <div className="row-fluid"> <div className="span2">changes</div> <div className="span10"> <button type="button" className='btn btn-small btn-secondary' onClick={this.toggleJSON.bind(this)}> {codeVisible ? 'Close JSON' : 'View JSON'} </button> </div> </div> <ChangesCodeTransition codeVisible={this.state.codeVisible} code={this.getChangeCode()} /> </div> </div> ); } } ChangeRow.propTypes = { change: PropTypes.object, databaseName: PropTypes.string.isRequired };
packages/mineral-ui-icons/src/IconPool.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 IconPool(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M22 21c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.08.64-2.19.64-1.11 0-1.73-.37-2.18-.64-.37-.23-.6-.36-1.15-.36s-.78.13-1.15.36c-.46.27-1.08.64-2.19.64v-2c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36v2zm0-4.5c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36s-.78.13-1.15.36c-.47.27-1.09.64-2.2.64v-2c.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36v2zM8.67 12c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.12-.07.26-.15.41-.23L10.48 5C8.93 3.45 7.5 2.99 5 3v2.5c1.82-.01 2.89.39 4 1.5l1 1-3.25 3.25c.31.12.56.27.77.39.37.23.59.36 1.15.36z"/><circle cx="16.5" cy="5.5" r="2.5"/> </g> </Icon> ); } IconPool.displayName = 'IconPool'; IconPool.category = 'places';
app/components/ExerciseDetail/ExerciseDetail.js
sunnymis/Swoleciety
import React from 'react'; import PropTypes from 'prop-types'; require('./ExerciseDetail.scss'); ExerciseDetail.defaultProps = { type: '', value: 0, units: '', }; ExerciseDetail.propTypes = { type: PropTypes.string, value: PropTypes.number, units: PropTypes.string, }; function ExerciseDetail(props) { return ( <div className="exercise-detail"> <h2 className="type">{props.type}</h2> <h3 className="value"> {props.value} <span className="units">{props.units}</span> </h3> </div> ); }; export default ExerciseDetail;
examples/using-type-definitions/src/pages/page-2.js
ChristopherBiscardi/gatsby
import React from 'react' import { Link } from 'gatsby' import Layout from '../components/layout' import SEO from '../components/seo' const SecondPage = () => ( <Layout> <SEO title="Page two" /> <h1>Hi from the second page</h1> <p>Welcome to page 2</p> <Link to="/">Go back to the homepage</Link> </Layout> ) export default SecondPage
src/components/Menu.js
Greennav/greennav
import React, { Component } from 'react'; import { Tabs, Tab } from 'material-ui/Tabs'; import AutoComplete from 'material-ui/AutoComplete'; import Slider from 'material-ui/Slider'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import FontIcon from 'material-ui/FontIcon'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import Paper from 'material-ui/Paper'; import { green700 } from 'material-ui/styles/colors'; import ReachabilityTab from './ReachabilityTab'; import PropTypes from 'prop-types'; const MILES_TO_KM = 1.609344; const KM_TO_MILES = 1 / 1.609344; const styles = { container: { display: 'flex', zIndex: 1, minWidth: '300px' }, tabs: { flex: '1', display: 'flex', flexDirection: 'column' }, tabsContainer: { flex: '1', display: 'flex', flexDirection: 'column', overflowY: 'auto' }, menu: { margin: '10px 20px 30px' }, slider: { marginBottom: '25px' }, reachabilitySlider: { marginBottom: '0px' }, autoCompleteWrapper: { position: 'relative', display: 'flex' }, stopoversInput: { paddingRight: '45px', }, removeStopoverBtn: { position: 'absolute', right: 0, bottom: '5px' }, addStopoverBtn: { margin: '10px 0' }, batteryLevel: { display: 'flex', justifyContent: 'space-between' }, batteryLevelValue: { fontWeight: 'bold', color: green700, fontSize: '14px' }, textField: { display: 'inherit', position: 'relative', marginBottom: '25px' } }; export default class Menu extends Component { constructor(props) { super(props); this.state = { vehicle: 0, open: this.props.open, dataSource: [], autoCompletes: [{ id: 1, label: 'From', route: '' }, { id: 2, label: 'To', route: '' }], batteryPecentage: 100, batteryLevel: 1.0, remainingRange: 0, checkMenuSelection: { from: 0, to: 0 }, }; this.autoCompleteId = 3; this.xhr = new XMLHttpRequest(); } getVehicles = () => [ 'Fiat Fiorino', 'Smart Roadster', 'Sam', 'Citysax', 'MUTE', 'Spyder-S', 'Think', 'Luis', 'STROMOS', 'Karabag Fiat 500E', 'Lupower Fiat 500E' ] getRoute = () => { const autoCompletes = this.state.autoCompletes; if (autoCompletes.every(elem => elem.route !== '') && (this.state.checkMenuSelection.from === 1) && this.state.checkMenuSelection.to === 1) { const routes = autoCompletes.map(elem => elem.route); this.props.getRoutes(routes); } else { this.props.handleIndicateStartSnackbarOpen(); } } getRangeVisualisation = () => { if (this.state.remainingRange > 0) { if (this.props.unitsType === 1) { this.props.getRangeVisualisation(this.state.remainingRange * MILES_TO_KM); } else { this.props.getRangeVisualisation(this.state.remainingRange); } } else { this.props.handleRemainingRangeSnackbarOpen(); } } getAllAutoCompletes = () => { const dataSourceConfig = { text: 'text', value: 'data', }; const allAutoCompletes = this.state.autoCompletes.map(autoComplete => ( <div style={styles.autoCompleteWrapper} key={`wrapper-${autoComplete.id}`}> <AutoComplete inputStyle={ this.isStopover(autoComplete.id) ? styles.stopoversInput : {} } key={autoComplete.id} floatingLabelText={autoComplete.label} onNewRequest={(req, index) => { // if index is not -1 and multiple suggestions with same value exits // then select the first one const route = index === -1 ? '' : this.state.dataSource[0].data.osm_id; const updatedAutoCompletes = this.state.autoCompletes.map((autoCompleteElem) => { if (autoCompleteElem.id === autoComplete.id) { return Object.assign({}, autoCompleteElem, { route }); } return autoCompleteElem; }); this.setState({ autoCompletes: updatedAutoCompletes }); const newCheckMenuSelection = this.state.checkMenuSelection; if (autoComplete.id === 1) { newCheckMenuSelection.from = 1; } else if (autoComplete.id === 2) { newCheckMenuSelection.to = 1; } this.setState({ checkMenuSelection: newCheckMenuSelection }); }} onClose={() => { const newCheckMenuSelection = this.state.checkMenuSelection; if (autoComplete.id === 1) { newCheckMenuSelection.from = 0; } else if (autoComplete.id === 2) { newCheckMenuSelection.to = 0; } this.setState({ checkMenuSelection: newCheckMenuSelection }); }} dataSource={this.state.dataSource} onUpdateInput={this.handleUpdate} dataSourceConfig={dataSourceConfig} fullWidth /> {this.isStopover(autoComplete.id) ? <IconButton style={styles.removeStopoverBtn} onClick={() => { setTimeout(() => { this.setState( { autoCompletes: this.state.autoCompletes.filter(elem => elem.id !== autoComplete.id) } ); }, 200); }} > <FontIcon className="material-icons">remove_circle</FontIcon> </IconButton> : '' } </div> )); return allAutoCompletes; } isStopover = id => (id !== 1 && id !== 2) handleUpdate = (address) => { // dont make any req if autocomplete is empty if (!address.length) { return; } if (this.xhr.readyState !== 0 || this.xhr.readyState !== 4) { this.xhr.abort(); } this.xhr.onreadystatechange = () => { if (this.xhr.readyState === 4 && this.xhr.status === 200) { const places = JSON.parse(this.xhr.responseText).map(place => ( { text: place.display_name, data: { osm_id: place.osm_id, longitude: place.lon, latitude: place.lat } } )); this.setState({ dataSource: places }); } }; this.xhr.onerror = () => { this.props.handleErrorFailedRequestOpen('Request Failed'); }; this.xhr.open('GET', `${this.props.autoCompleteAddress}search/${encodeURIComponent(address)}`, true); this.xhr.send(); } toggle = (callback) => { this.setState({ open: !this.state.open }, callback); } vehicleChange = (event, index, value) => { this.setState({ vehicle: value }); } convertUnits = (newUnitsType) => { if (newUnitsType !== this.props.unitsType && this.state.remainingRange > 0) { if (newUnitsType === 1) { this.setState(prevState => ({ remainingRange: prevState.remainingRange * KM_TO_MILES })); } else { this.setState(prevState => ({ remainingRange: prevState.remainingRange * MILES_TO_KM })); } } } updateBatterySlider = (event, value) => { // TODO: Set remainingRange to distance in km/miles based on batteryLevel and car model this.setState({ batteryPecentage: parseInt(value * 100, 10), batteryLevel: value, remainingRange: parseInt(value * 100, 10), }); } updateRemainingRange = (event, value) => { // TODO: Set remainingRange to distance in km/miles based on batteryLevel and car model this.setState({ remainingRange: parseFloat(value) }); } render() { return ( <Paper style={this.state.open ? styles.container : { display: 'none' }} zDepth={5} rounded={false}> <Tabs contentContainerStyle={styles.tabsContainer} inkBarStyle={styles.active} style={styles.tabs} > <Tab label="Route"> <div style={styles.menu}> {this.getAllAutoCompletes()} <div> <FlatButton style={styles.addStopoverBtn} label="Add Stopover" onClick={() => { const soLength = this.state.autoCompletes.length; this.setState( { autoCompletes: [ ...this.state.autoCompletes.slice(0, soLength - 1), { id: this.autoCompleteId, label: 'Over', route: '' }, this.state.autoCompletes[soLength - 1] ] }, () => { this.autoCompleteId += 1; } ); }} labelStyle={{ textTransform: 'none' }} icon={<FontIcon className="material-icons">add_circle</FontIcon>} /> </div> <SelectField floatingLabelText="Vehicle" value={this.state.vehicle} onChange={this.vehicleChange} maxHeight={210} fullWidth > {this.getVehicles().map((vehicle, index) => ( <MenuItem key={vehicle} value={index} primaryText={vehicle} /> ))} </SelectField> <p style={styles.batteryLevel}> <span>Battery Level</span> <span style={styles.batteryLevelValue} ref={node => (this.batteryLevel = node)} > {`${this.state.batteryPecentage}%`} </span> </p> <Slider onChange={this.updateBatterySlider} value={this.state.batteryLevel} sliderStyle={styles.slider} /> <RaisedButton label="Get Route" onClick={this.getRoute} icon={<FontIcon className="material-icons">near_me</FontIcon>} /> </div> </Tab> <Tab label="Reachability" style={styles.tab} > <ReachabilityTab batteryLevel={this.state.batteryLevel} batteryPecentage={this.state.batteryPecentage} remainingRange={this.state.remainingRange} updateRemainingRange={this.updateRemainingRange} updateBatterySlider={this.updateBatterySlider} rangePolygonVisible={this.props.rangePolygonVisible} getRangeVisualisation={this.getRangeVisualisation} hideRangeVisualisation={this.props.hideRangeVisualisation} getVehicles={this.getVehicles} vehicle={this.state.vehicle} vehicleChange={this.vehicleChange} updateRangeFromField={val => this.props.updateRangeFromField(val)} updateRangeFromSelected={e => this.props.updateRangeFromSelected(e)} rangeFromField={this.props.rangeFromField} updateRangeToField={val => this.props.updateRangeToField(val)} updateRangeToSelected={e => this.props.updateRangeToSelected(e)} rangeToField={this.props.rangeToField} setRangePolygonAutocompleteOrigin={val => this.props.setRangePolygonAutocompleteOrigin(val)} setRangePolygonAutocompleteDestination={val => this.props.setRangePolygonAutocompleteDestination(val)} /> </Tab> </Tabs> </Paper> ); } } Menu.propTypes = { open: PropTypes.bool, unitsType: PropTypes.number.isRequired, autoCompleteAddress: PropTypes.string.isRequired, rangePolygonVisible: PropTypes.bool.isRequired, getRoutes: PropTypes.func.isRequired, getRangeVisualisation: PropTypes.func.isRequired, hideRangeVisualisation: PropTypes.func.isRequired, rangeFromField: PropTypes.string.isRequired, updateRangeFromField: PropTypes.func.isRequired, updateRangeFromSelected: PropTypes.func.isRequired, rangeToField: PropTypes.string.isRequired, updateRangeToField: PropTypes.func.isRequired, updateRangeToSelected: PropTypes.func.isRequired, setRangePolygonAutocompleteOrigin: PropTypes.func.isRequired, setRangePolygonAutocompleteDestination: PropTypes.func.isRequired, handleIndicateStartSnackbarOpen: PropTypes.func.isRequired, handleRemainingRangeSnackbarOpen: PropTypes.func.isRequired, handleErrorFailedRequestOpen: PropTypes.func.isRequired, }; Menu.defaultProps = { open: true };
src/components/Protein/Isoforms/Viewer/index.js
ProteinsWebTeam/interpro7-client
// @flow import React from 'react'; import T from 'prop-types'; import { format } from 'url'; import { createSelector } from 'reselect'; import loadData from 'higherOrder/loadData'; import descriptionToPath from 'utils/processDescription/descriptionToPath'; import NumberComponent from 'components/NumberComponent'; import { groupByEntryType, byEntryType, } from 'components/Related/DomainsOnProtein'; import Loading from 'components/SimpleCommonComponents/Loading'; import loadable from 'higherOrder/loadable'; import { foundationPartial } from 'styles/foundation'; import style from '../style.css'; const f = foundationPartial(style); const ProtVista = loadable({ loader: () => import(/* webpackChunkName: "protvista" */ 'components/ProtVista'), }); /*:: type Feature = { accession: string, name: string, source_database: string, type: string, children: Array<Object>, integrated: ?string, locations: [], } type FeatureMap = { [string]: Feature, } type IsoformPayload = { accession: string, length: number, protein_acc: string, sequence: string, features: FeatureMap, } */ const features2protvista = (features /*: FeatureMap */) => { // prettier-ignore const featArray /*: Array<Feature> */ = (Object.values(features || {})/*: any */); const integrated = []; for (const feature of featArray) { if (feature.integrated && feature.integrated in features) { const parent = features[feature.integrated]; if (!('children' in parent)) { parent.children = []; } if (parent.children.indexOf(feature) === -1) parent.children.push(feature); integrated.push(feature); } } const interpro = featArray.filter(({ accession }) => accession.toLowerCase().startsWith('ipr'), ); const groups = groupByEntryType(interpro); const unintegrated = featArray.filter( (f) => interpro.indexOf(f) === -1 && integrated.indexOf(f) === -1, ); return [...Object.entries(groups), ['unintegrated', unintegrated]].sort( byEntryType, ); }; const Viewer = ( { isoform, data, } /*: {isoform: string, data: {loading: boolean, payload: IsoformPayload}} */, ) => { if (!isoform) return null; if ( !data || data.loading || !data.payload || !data.payload.accession || isoform !== data.payload.accession ) return <Loading />; const { accession, length, sequence, features } = data.payload; const dataProtvista = features2protvista(features); return ( <div className={f('isoform-panel', 'row')}> <div className={f('column')}> <header> <span className={f('key')}>Isoform:</span>{' '} <span className={f('id')}>{accession}</span> <br /> <span className={f('key')}>Length:</span>{' '} <NumberComponent>{length}</NumberComponent> </header> <ProtVista protein={{ sequence, length: sequence.length }} data={dataProtvista} title="Entry matches to this Isoform" /> </div> </div> ); }; Viewer.propTypes = { isoform: T.string, data: T.shape({ loading: T.bool, payload: T.object, }), }; const mapStateToProps = createSelector( (state) => state.customLocation.search, ({ isoform }) => ({ isoform }), ); const getIsoformURL = createSelector( (state) => state.settings.api, (state) => state.customLocation.description, (state) => state.customLocation.search, ( { protocol, hostname, port, root }, { protein: { accession } }, { isoform }, ) => { const description = { main: { key: 'protein' }, protein: { db: 'uniprot', accession }, }; return format({ protocol, hostname, port, pathname: root + descriptionToPath(description), query: { isoforms: isoform, }, }); }, ); export default loadData({ getUrl: getIsoformURL, mapStateToProps })(Viewer);
example/src/screens/types/CustomButtonScreen.js
eeynard/react-native-navigation
import React from 'react'; import { View, StyleSheet, Text, TouchableOpacity, Button } from 'react-native'; import {Navigation} from 'react-native-navigation'; let navigator; const CustomButton = ({text}) => <TouchableOpacity style={[styles.buttonContainer]} onPress={() => navigator.pop()} > <View style={styles.button}> <Text style={{ color: 'white' }}>{text}</Text> </View> </TouchableOpacity>; Navigation.registerComponent('CustomButton', () => CustomButton); export default class CustomButtonScreen extends React.Component { static navigatorButtons = { rightButtons: [ { id: 'custom-button', component: 'CustomButton', passProps: { text: 'Hi!' } } ] }; componentWillMount() { navigator = this.props.navigator; } render() { return ( <View style={styles.container}> <Text>Custom Left Button</Text> </View> ); } componentWillUnmount() { navigator = null; } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'white' }, buttonContainer: { width: 48, height: 48, justifyContent: 'center', alignItems: 'center' }, button: { backgroundColor: 'tomato', width: 34, height: 34, borderRadius: 34 / 2, overflow: 'hidden', justifyContent: 'center', alignItems: 'center' } });
Project 06 - Video background/src/containers/Home.js
DCKT/30DaysofReactNative
import React from 'react' import { View, StyleSheet, StatusBar, Image } from 'react-native' import { Button, Text as NText } from 'native-base' import SplashScreen from 'react-native-splash-screen' import Video from 'react-native-video' class Home extends React.Component { componentDidMount () { SplashScreen.hide() } static navigationOptions = { header: { visible: false } } render () { return ( <View style={{ flex: 1, justifyContent: 'space-between' }}> <StatusBar backgroundColor='transparent' barStyle='light-content' /> <Video source={require('../assets/moments.mp4')} // Can be a URL or a local file. ref={(ref) => { this.player = ref }} // Store reference rate={1.0} // 0 is paused, 1 is normal. volume={1.0} // 0 is muted, 1 is normal. muted={true} // Mutes the audio entirely. // Pauses playback entirely. resizeMode='cover' // Fill the whole screen at aspect ratio.* repeat={true} // Repeat forever. playInBackground={false} // Audio continues to play when app entering background. playWhenInactive={false} // [iOS] Video continues to play when control or notification center are shown. progressUpdateInterval={250.0} // [iOS] Interval to fire onProgress (default to ~250ms) style={styles.backgroundVideo} /> <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}> <Image source={require('../assets/logos/spotify_logo.png')} resizeMode='contain' style={{ width: 300 }} /> </View> <View style={{ marginHorizontal: 10, marginBottom: 25 }}> <Button success block style={{ marginBottom: 10 }}> <NText>Login</NText> </Button> <Button light block> <NText style={{ color: '#1ED760' }}>Sign up</NText> </Button> </View> </View> ) } } const styles = StyleSheet.create({ backgroundVideo: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0 } }) export default Home
app/javascript/mastodon/components/permalink.js
riku6460/chikuwagoddon
import React from 'react'; import PropTypes from 'prop-types'; export default class Permalink extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { className: PropTypes.string, href: PropTypes.string.isRequired, to: PropTypes.string.isRequired, children: PropTypes.node, onInterceptClick: PropTypes.func, }; handleClick = e => { if (this.props.onInterceptClick && this.props.onInterceptClick()) { e.preventDefault(); return; } if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(this.props.to); } } render () { const { href, children, className, onInterceptClick, ...other } = this.props; return ( <a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}> {children} </a> ); } }
src/components/Banner/Banner.react.js
HackCWRU/HackCWRU-Website
import React from 'react'; import styles from 'components/Banner/Banner.scss'; export default class Banner extends React.Component { render() { return ( <div className={styles.banner}> {this.props.children} </div> ) } }
app/MnmNavigationBarRouteMapper.js
alvaromb/mnm
/*global require, module*/ 'use strict'; import React from 'react' import { StyleSheet, Text, View, TouchableOpacity } from 'react-native' var NavigationBarRouteMapper = { LeftButton: function(route, navigator, index, navState) { if (index === 0) { return null; } var previousRoute = navState.routeStack[index - 1]; return ( <TouchableOpacity onPress={() => navigator.pop()}> <View style={styles.navBarLeftButton}> <Text style={[styles.navBarText, styles.navBarButtonText]}> {previousRoute.title} </Text> </View> </TouchableOpacity> ); }, RightButton: function() {}, Title: function(route, navigator, index, navState) { return ( <Text style={[styles.navBarText, styles.navBarTitleText]}> {route.title} </Text> ); }, }; var styles = StyleSheet.create({}); module.exports = NavigationBarRouteMapper;
stories/size-and-position.js
bokuweb/react-rnd
/* eslint-disable */ import React from 'react'; import Rnd from '../src'; const style = { display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'solid 1px #ddd', background: '#f0f0f0', }; export default class Example extends React.Component { constructor() { super(); this.state = { width: 100, height: 120, x: 0, y: 0, }; } render() { return ( <Rnd style={style} size={{ width: this.state.width, height: this.state.height, }} bounds="parent" position={{ x: this.state.x, y: this.state.y, }} onDragStop={(e, d) => { this.setState({ x: d.x, y: d.y }) }} onResize={(e, direction, ref, delta, position) => { this.setState({ width: ref.offsetWidth, height: ref.offsetHeight, ...position, }); }} > 001 </Rnd> ); } }
docs/src/components/Docs/Usage/index.js
michalko/draft-wyswig
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { EditorState, convertToRaw, ContentState, Modifier } from 'draft-js'; import draftToHtml from 'draftjs-to-html'; import htmlToDraft from 'html-to-draftjs'; import { Editor } from 'react-draft-wysiwyg'; import Codemirror from 'react-codemirror'; import sampleEditorContent from '../../../util/sampleEditorContent'; const Usage = () => ( <div className="docs-section"> <h2>Using editor component</h2> <div className="docs-desc">Editor can be simply imported and used as a React Component. Make sure to also include react-draft-wysiwyg.css from node_modules.</div> <Codemirror value={ 'import React, { Component } from \'react\';\n' + 'import { Editor } from \'react-draft-wysiwyg\';\n' + 'import \'../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css\';\n' + '\n\n' + 'const EditorComponent = () => <Editor />' } options={{ lineNumbers: true, mode: 'jsx', readOnly: true, }} /> </div> ); export default Usage;
packages/reactor-kitchensink/src/examples/Charts/Pie/Spie/Spie.js
sencha/extjs-reactor
import React, { Component } from 'react'; import { Container } from '@extjs/ext-react'; import { Polar } from '@extjs/ext-react-charts'; import ChartToolbar from '../../ChartToolbar'; export default class Spie extends Component { store = Ext.create('Ext.data.Store', { fields: ['os', 'data1', 'data2'], data: [ { os: 'Android', data1: 68.3, data2: 150 }, { os: 'iOS', data1: 17.9, data2: 200 }, { os: 'Windows Phone', data1: 10.2, data2: 250 }, { os: 'BlackBerry', data1: 1.7, data2: 90 }, { os: 'Others', data1: 1.9, data2: 190 } ] }) state = { theme: 'default' } changeTheme = theme => this.setState({ theme }) render() { const { theme } = this.state; return ( <Container padding={!Ext.os.is.Phone && 10} layout="fit"> <ChartToolbar onThemeChange={this.changeTheme} theme={theme}/> <Polar shadow store={this.store} theme={theme} legend={{ type: 'sprite', docked: 'bottom', marker: { size: 16 } }} interactions={['rotate', 'itemhighlight']} series={[{ type: 'pie', animation: { easing: 'easeOut', duration: 500 }, angleField: 'data1', // bind pie slice angular span to market share radiusField: 'data2', // bind pie slice radius to growth rate clockwise: false, highlight: { margin: 20 }, label: { field: 'os', // bind label text to name display: 'outside', fontSize: 14 }, style: { strokeStyle: 'white', lineWidth: 1 }, tooltip: { trackMouse: true, renderer: (tooltip, record) => { tooltip.setHtml(record.get('os') + ': ' + record.get('data1') + '%') } } }]} /> </Container> ) } }
src/components/article/title-row-above.js
hanyulo/twreporter-react
import { colors, componentMargin, globalColor, layout, typography } from '../../themes/common-variables' import { LINK_PREFIX } from '../../constants/index' import Link from 'react-router/lib/Link' import React from 'react' import { date2yyyymmdd } from '../../utils/index' import get from 'lodash/get' import { screen } from '../../themes/screen' import styled from 'styled-components' import PropTypes from 'prop-types' const _ = { get } const colorSelector = (props, defaultColor) => { if (props.color) { return props.color } return defaultColor } // ############################# // Containers // ############################# const Container = styled.div` display: block; margin: 0 auto 24px auto; ${screen.desktopAbove` width: ${layout.desktop.small}; `} ${screen.tablet` width: ${layout.tablet.small}; `} ${screen.mobile` margin: 0 ${componentMargin.horizontalMargin} 24px ${componentMargin.horizontalMargin}; `} ` const HeaderContainer = styled.hgroup`` const FirstRow = styled.div` margin-top: 10px; margin-bottom: 12.5px; ` // ############################# // Fundemenatal Elements // ############################# const HeaderElementBlock = styled.div` display: inline-block; ` const Title = HeaderElementBlock.extend` margin: 0; font-weight: ${typography.font.weight.bold}; line-height: 1.4; font-size: 42px; color: ${props => (colorSelector(props, globalColor.textColor))}; ${screen.desktop` font-size: 38px; `} ${screen.tablet` font-size: 38px; `} ${screen.mobile` font-size: ${typography.font.size.xLarger}; `} ` const Subtitle = HeaderElementBlock.extend` color: ${props => (colorSelector(props, colors.gray.gray50))}; font-size: ${typography.font.size.medium}; font-size: ${typography.font.size.medium}; ` const Topic = HeaderElementBlock.extend` > a { text-decoration: none !important; border: 0 !important; transition: all 0s ease 0s !important; &:after { content: normal !important; } } ` const TopicContent = styled.span` color: ${props => (colorSelector(props, colors.red.rustyRed))}; font-size: ${typography.font.size.medium}; font-weight: ${typography.font.weight.bold}; ` const RightArrow = styled.div` border: solid ${props => (props.color ? props.color : colors.red.rustyRed)}; border-width: 0 2px 2px 0; display: inline-block; padding: 4px; transform: rotate(-45deg); margin: 0 10px 1px 3px; ` const TopicBlock = ({ topic, color }) => { const topicName = _.get(topic, 'topicName') const topicSlug = _.get(topic, 'slug') if (topicName) { return ( <Topic> <Link to={`${LINK_PREFIX.TOPICS}${topicSlug}`} > <TopicContent color={color} > {topicName} <RightArrow color={color}/> </TopicContent> </Link> </Topic> ) } return null } TopicBlock.defaultProps = { color: '', topic: {} } TopicBlock.propTypes = { color: PropTypes.string, topic: PropTypes.object } const SubtitleBlock = ({ subtitle, color }) => { if (subtitle) { return ( <Subtitle itemProp="alternativeHeadline" color={color} > {subtitle} </Subtitle> ) } return null } SubtitleBlock.defaultProps = { color: '', subtitle: '' } SubtitleBlock.propTypes = { color: PropTypes.string, subtitle: PropTypes.string } const HeaderGroup = ({ fontColorSet, article, topic }) => { const subtitle = _.get(article, 'subtitle', '') const title = _.get(article, 'title', '') const { topicFontColor, titleFontColor, subtitleFontColor } = fontColorSet return ( <HeaderContainer> <FirstRow> <TopicBlock topic={topic} color={topicFontColor} /> <SubtitleBlock subtitle={subtitle} color={subtitleFontColor} /> </FirstRow> <Title color={titleFontColor} > {title} </Title> </HeaderContainer> ) } HeaderGroup.defaultProps = { fontColorSet: {}, topic: {}, article: {} } HeaderGroup.propTypes = { fontColorSet: PropTypes.object, topic: PropTypes.object, article: PropTypes.object } const TitleRowAbove = ({ article, canonical, fontColorSet, topic }) => { const updatedAt = _.get(article, 'updatedAt') || _.get(article, 'publishedDate') return ( <Container> <HeaderGroup fontColorSet={fontColorSet} topic={topic} article={article} /> <div itemProp="publisher" itemScope itemType="http://schema.org/Organization"> <meta itemProp="name" content="報導者" /> <meta itemProp="email" content="contact@twreporter.org" /> <link itemProp="logo" href="https://www.twreporter.org/asset/logo-large.png" /> <link itemProp="url" href="https://www.twreporter.org/" /> </div> <link itemProp="mainEntityOfPage" href={canonical} /> <meta itemProp="dateModified" content={date2yyyymmdd(updatedAt, '-')} /> </Container> ) } TitleRowAbove.defaultProps = { article: {}, topic: {}, canonical: '', fontColorSet: {} } TitleRowAbove.propTypes = { article: PropTypes.object, topic: PropTypes.object, canonical: PropTypes.string, fontColorSet: PropTypes.object } export default TitleRowAbove
src/routes/drawer/index.js
ChrisWC/MaterL
import React from 'react'; import DrawerRoute from './Drawer'; import fetch from '../../core/fetch'; export default { path: '/drawer', async action() { return <DrawerRoute />; }, };
src/parser/warlock/demonology/modules/pets/PetTimelineTab/TabComponent/KeyCastsRow.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SpellIcon from 'common/SpellIcon'; import Tooltip from 'common/Tooltip'; import { EventType } from 'parser/core/Events'; const KeyCastsRow = props => { const { className, events, start, totalWidth, secondWidth } = props; return ( <div className={`events ${className || ''}`} style={{ width: totalWidth }}> {events.map((event, index) => { if (event.type === EventType.Cast) { const left = (event.timestamp - start) / 1000 * secondWidth; const tooltipInfo = []; if (event.extraInfo) { tooltipInfo.push(event.extraInfo); } if (event.nearbyCasts) { tooltipInfo.push(`This cast overlaps with following casts: ${event.nearbyCasts.join(', ')}.`); } const hasTooltip = tooltipInfo.length > 0; return ( <div key={index} style={{ left, top: -1, zIndex: (event.important) ? 20 : 10, }} > {hasTooltip ? ( <Tooltip content={tooltipInfo.join('\n')}> <div> <SpellIcon id={event.abilityId} className={event.important && 'enhanced'} /> </div> </Tooltip> ) : ( <SpellIcon id={event.abilityId} className={event.important && 'enhanced'} /> )} </div> ); } else if (event.type === 'duration') { const left = (event.timestamp - start) / 1000 * secondWidth; const maxWidth = totalWidth - left; // don't expand beyond the container width const width = Math.min(maxWidth, (event.endTimestamp - event.timestamp) / 1000 * secondWidth); return ( <div key={index} style={{ left, width, background: 'rgba(133, 59, 255, 0.7)', }} data-effect="float" /> ); } return null; })} </div> ); }; KeyCastsRow.propTypes = { className: PropTypes.string, events: PropTypes.array, start: PropTypes.number.isRequired, totalWidth: PropTypes.number.isRequired, secondWidth: PropTypes.number.isRequired, }; export default KeyCastsRow;
src/server/server.js
Coderockr/redux-skeleton
import path from 'path'; import express from 'express'; import webpack from 'webpack'; import webpackMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import config from '../../webpack.config.dev'; import cookieParser from 'cookie-parser'; import helmet from 'helmet'; import hpp from 'hpp'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import compression from 'compression'; import React from 'react'; import ReactDOM from 'react-dom/server'; import { createMemoryHistory, RouterContext, match } from 'react-router'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import { trigger } from 'redial'; import { callAPIMiddleware } from '../middleware/callAPIMiddleware'; import { StyleSheetServer } from 'aphrodite'; import { configureStore } from '../store'; import Helm from 'react-helmet'; // because we are already using helmet import reducer from '../createReducer'; import createRoutes from '../routes/root'; const isDeveloping = process.env.NODE_ENV == 'development'; const port = process.env.PORT || 5000; const server = global.server = express(); // Security server.disable('x-powered-by'); server.set('port', port); server.use(bodyParser.urlencoded({ extended: false })); server.use(bodyParser.json()); server.use(hpp()); server.use(helmet.contentSecurityPolicy({ defaultSrc: ["'self'"], scriptSrc: ["'self'"], styleSrc: ["'self'"], imgSrc: ["'self'"], connectSrc: ["'self'", 'ws:'], fontSrc: ["'self'"], objectSrc: ["'none'"], mediaSrc: ["'none'"], frameSrc: ["'none'"], })); server.use(helmet.xssFilter()); server.use(helmet.frameguard('deny')); server.use(helmet.ieNoOpen()); server.use(helmet.noSniff()); server.use(cookieParser()); server.use(compression()); // API server.use('/api/v0/posts', require('./api/posts')); server.use('/api/v0/post', require('./api/post')); // Stub for assets, in case running in dev mode. let assets; // Webpack (for development) if (isDeveloping) { server.use(morgan('dev')); const compiler = webpack(config); const middleware = webpackMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: 'src', stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: true, modules: false, }, }); server.use(middleware); server.use(webpackHotMiddleware(compiler, { log: console.log, })); } else { const buildPath = require('../../webpack.config.prod').output.path; assets = require('../../assets.json'); server.use(morgan('combined')); server.use('/build/static', express.static(buildPath)); } // Render Document (include global styles) const renderFullPage = (data, initialState, assets) => { const head = Helm.rewind(); // Included are some solid resets. Feel free to add normalize etc. return ` <!DOCTYPE html> <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> ${head.title.toString()} <meta name="viewport" content="width=device-width, initial-scale=1" /> ${head.meta.toString()} ${head.link.toString()} <style> html { box-sizing: border-box; } *, *::before, *::after { box-sizing: border-box; } @at-root { @-moz-viewport { width: device-width; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } @-webkit-viewport { width: device-width; } @viewport { width: device-width; } } html { font-size: 100%; -ms-overflow-style: scrollbar; -webkit-tap-highlight-color: rgba(0,0,0,0); height: 100%; } body { font-size: 1rem; background-color: #fff; color: #555; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif; } [tabindex="-1"]:focus { outline: none !important; } /* Typography */ h1, h2, h3, h4, h5, h6 { margin: 0; letter-spacing: -0.03em; font-weight: bold; } p { margin: 0; } abbr[title], abbr[data-original-title] { cursor: help; border-bottom: 1px dotted #eee; } address { margin-bottom: 1rem; font-style: normal; line-height: inherit; } ol, ul, dl { margin-top: 0; margin-bottom: 1rem; } ol ol, ul ul, ol ul, ul ol { margin-bottom: 0; } dt { font-weight: bold; } dd { margin-bottom: .5rem; margin-left: 0; } blockquote { margin: 0 0 1rem; } /* Links */ a, a:hover, a:focus { text-decoration: none; } /* Code */ pre { margin: 0; /*margin-bottom: 1rem;*/ } /* Figures & Images */ figure { margin: 0 0 1rem; } img { vertical-align: middle; } [role="button"] { cursor: pointer; } a, area, button, [role="button"], input, label, select, summary, textarea { touch-action: manipulation; } /* Forms */ label { display: inline-block; margin-bottom: .5rem; } button:focus { outline: 1px dotted; outline: 5px auto -webkit-focus-ring-color; } input, button, select, textarea { margin: 0; line-height: inherit; border-radius: 0; } textarea { resize: vertical; } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: .5rem; font-size: 1.5rem; line-height: inherit; } input[type="search"], input[type="text"], textarea { box-sizing: inherit; -webkit-appearance: none; } [hidden] { display: none !important; } body, button, input, textarea { font-family: font-family: 'Helvetica Neue', Helvetica, sans-serif;; } a,a:visited { text-decoration: none; } </style> <style data-aphrodite>${data.css.content}</style> </head> <body> <div id="root">${data.html}</div> <script>window.renderedClassNames = ${JSON.stringify(data.css.renderedClassNames)};</script> <script>window.INITIAL_STATE = ${JSON.stringify(initialState)};</script> <script src="${ isDeveloping ? '/build/static/vendor.js' : assets.vendor.js}"></script> <script src="${ isDeveloping ? '/build/static/main.js' : assets.main.js}"></script> </body> </html> `; }; // SSR Logic server.get('*', (req, res) => { const store = configureStore(); const routes = createRoutes(store); const history = createMemoryHistory(req.path); const { dispatch } = store; match({ routes, history }, (err, redirectLocation, renderProps) => { if (err) { console.error(err); return res.status(500).send('Internal server error'); } if (!renderProps) return res.status(404).send('Not found'); const { components } = renderProps; // Define locals to be provided to all lifecycle hooks: const locals = { path: renderProps.location.pathname, query: renderProps.location.query, params: renderProps.params, // Allow lifecycle hooks to dispatch Redux actions: dispatch, }; trigger('fetch', components, locals) .then(() => { const initialState = store.getState(); const InitialView = ( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); // just call html = ReactDOM.renderToString(InitialView) // to if you don't want Aphrodite. Also change renderFullPage // accordingly const data = StyleSheetServer.renderStatic( () => ReactDOM.renderToString(InitialView) ); res.status(200).send(renderFullPage(data, initialState, assets)); }) .catch(e => console.log(e)); }); }); // Listen server.listen(port, '0.0.0.0', function onStart(err) { if (err) { console.log(err); } console.info('==> 🌎 Listening on port %s.' + 'Open up http://0.0.0.0:%s/ in your browser.', port, port); }); module.exports = server;
shared/app/Tms/components/Icons/Restart.js
pebie/react-universally-node-config
import PropTypes from 'prop-types'; import React from 'react'; /** * Restart icon * * @return {jsx} */ const Restart = ({ svgClass, pathClass }) => (<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" className={svgClass} aria-labelledby="title desc" tabIndex="0" role="img" > <title id="title">Restart</title> <desc id="desc">Relancer la lecture du contenu au début</desc> <path className={pathClass} d={ 'M82.7 34L50.5 60.8V37c0-.8-.6-1.4-1.4-1.4h-8.5c-.7 ' + '0-1.4.6-1.4 1.4v54c0 .8.7 1.5 1.4 1.5h8.5c.8 0 1.4-.7 1.4-1.5V67.1L82.7 ' + '94c1.7 1.7 4.5 1.7 6.2 0V34c-1.7-1.7-4.5-1.7-6.2 0z' } /> <path className={pathClass} d={ 'M64 0C28.8 0 0 28.8 0 64c0 35.3 28.8 64 64 64 35.3 0 64-28.7 64-64 0-35.2-28.7-64-64-64zm0 ' + '8.9c30.5 0 55.1 24.6 55.1 55.1S94.5 119.1 64 119.1 8.9 94.5 8.9 64 33.5 8.9 64 8.9z' } /> </svg>); /** * PropTypes * * @type {string} svgClass * @type {string} pathClass */ Restart.propTypes = { svgClass: PropTypes.string, pathClass: PropTypes.string, }; export default Restart;
examples/official-storybook/components/addon-a11y/Button.js
storybooks/storybook
import React from 'react'; import PropTypes from 'prop-types'; const styles = { button: { padding: '12px 6px', fontSize: '12px', lineHeight: '16px', borderRadius: '5px', }, ok: { backgroundColor: '#028402', color: '#ffffff', }, wrong: { color: '#ffffff', backgroundColor: '#4caf50', }, }; function Button({ content, disabled, contrast }) { return ( <button type="button" style={{ ...styles.button, ...styles[contrast], }} disabled={disabled} > {content} </button> ); } Button.propTypes = { content: PropTypes.string, disabled: PropTypes.bool, contrast: PropTypes.oneOf(['ok', 'wrong']), }; Button.defaultProps = { content: 'null', disabled: false, contrast: 'ok', }; export default Button;
source/components/Value.js
cloud-walker/react-inspect
import React from 'react' const Component = ({children, type, theme}) => ( <span style={{ fontWeight: 'bold', color: (() => { switch (theme) { case 'gloom': { switch (type) { case 'string': return '#6DFEDF' case 'number': return '#FFDB7D' case 'function': return '#ED4781' default: return '#AE81FF' } } default: { switch (type) { case 'string': return 'green' case 'number': return 'orange' case 'function': return 'magenta' default: return 'purple' } } } })(), }} > {children} </span> ) Component.displayName = 'ReactInspectValue' export default Component
src/parser/warlock/demonology/modules/azerite/UmbralBlaze.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SPELLS from 'common/SPELLS'; import { formatThousands } from 'common/format'; import TraitStatisticBox from 'interface/others/TraitStatisticBox'; import ItemDamageDone from 'interface/ItemDamageDone'; /* Umbral Blaze: Your Hand of Guldan has a 15% chance to burn its target for X additional Shadowflame damage every 2 sec for 6 sec. */ class UmbralBlaze extends Analyzer { damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.UMBRAL_BLAZE.id); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.UMBRAL_BLAZE_DEBUFF), this.onUmbralBlazeDamage); } onUmbralBlazeDamage(event) { this.damage += event.amount + (event.absorbed || 0); } statistic() { return ( <TraitStatisticBox trait={SPELLS.UMBRAL_BLAZE.id} value={<ItemDamageDone amount={this.damage} />} tooltip={`${formatThousands(this.damage)} damage`} /> ); } } export default UmbralBlaze;
src/layout/Toolbar.js
davidcostadev/react-todo
import React from 'react' import '~assets/toolbar.scss' const ToolBar = ({title}) => { return <header className="toolbar">{title}</header> } export default ToolBar
gxa/src/main/javascript/bundles/differential-expression/src/DifferentialRouter.js
gxa/atlas
import React from 'react' import PropTypes from 'prop-types' import ReactTooltipStyleClass from './tooltip/ReactTooltipStyleClass' import Results from './DifferentialResults' import Facets from './facets-tree/DifferentialFacetsTree' import UrlManager from './urlManager' /* TODO if Solr queries get fast enough that we can: - split the two requests, so that the facets load first, initial results load second - a request to the server is done for every interaction with the facets tree - add counts to each facet and disable check boxes if count is 0 */ const equalsToOrIncludes = (obj, value) => { if (!!obj) { if (obj.constructor === Array) { return obj.includes(value) } else { return obj === value } } else { return false } } const addElementToObjectOfArrays = (obj, arrayName, element) => { if (!obj[arrayName]) { obj[arrayName] = [] } obj[arrayName].push(element) } const removeElementFromObjectOfArrays = (obj, arrayName, element) => { delete obj[arrayName].splice(obj[arrayName].indexOf(element), 1) if (obj[arrayName].length === 0) { delete obj[arrayName] } } const resultMatchesQuery = (result, query) => { if (Object.keys(query).length === 0) { return false } else { return Object.keys(query).every(facetName => query[facetName].some(facetItem => equalsToOrIncludes(result[facetName], facetItem) ) ) } } class DifferentialRouter extends React.Component { constructor(props) { super(props) const querySelect = UrlManager.parseDifferentialUrlParameter() if (!querySelect.kingdom) { querySelect.kingdom = props.facetsTreeData .find((facet) => facet.facetName === `kingdom`).facetItems .map((facetItem) => facetItem.name) } UrlManager.differentialPush(querySelect, true) this.state = { querySelect: querySelect } this._setChecked = this._setChecked.bind(this) } componentDidMount () { window.addEventListener( 'popstate', () => { this.setState({querySelect: UrlManager.parseDifferentialUrlParameter()}) }, false) } _setChecked (facetName, facetItemName, checked) { // Update URL const newQuerySelect = JSON.parse(JSON.stringify(this.state.querySelect)) if (checked) { addElementToObjectOfArrays(newQuerySelect, facetName, facetItemName) } else { removeElementFromObjectOfArrays(newQuerySelect, facetName, facetItemName) } // TODO Consider using https://github.com/reactjs/react-router UrlManager.differentialPush(newQuerySelect, false) this.setState({ querySelect: newQuerySelect }) } _filteredResults (query = this.state.querySelect) { return this.props.results.filter(result => resultMatchesQuery(result, query) ) } // Syncs tree data with URL (querySelect) and does some other smart things such as check/uncheck or disable facets based on // the user results (e.g. check & disable a facet if it’s shared by all results as a side effect of other choice) _prepareFacetTreeData(filteredResults) { return this.props.facetsTreeData.map((facet) => ({ facetName: facet.facetName, facetItems: facet.facetItems.map((facetItem) => { const querySelectAfterSwitchingThisFacetItem = JSON.parse(JSON.stringify(this.state.querySelect)) if (equalsToOrIncludes(querySelectAfterSwitchingThisFacetItem[facet.facetName], facetItem.name)) { removeElementFromObjectOfArrays(querySelectAfterSwitchingThisFacetItem, facet.facetName, facetItem.name) } else { addElementToObjectOfArrays(querySelectAfterSwitchingThisFacetItem, facet.facetName, facetItem.name) } const resultIdsAfterSwitchingThisFacetItem = this._filteredResults(querySelectAfterSwitchingThisFacetItem).map((result) => result.id).sort(); const currentResultIds = filteredResults.map((result) => result.id).sort() const sameResultsAfterSwitchingThisItem = JSON.stringify(resultIdsAfterSwitchingThisFacetItem) === JSON.stringify(currentResultIds) const noResultsAfterSwitchingThisItem = resultIdsAfterSwitchingThisFacetItem.length === 0 return { name: facetItem.name, value: facetItem.value, checked: equalsToOrIncludes(this.state.querySelect[facet.facetName], facetItem.name) || sameResultsAfterSwitchingThisItem, disabled: noResultsAfterSwitchingThisItem || sameResultsAfterSwitchingThisItem } }) })) } render () { const filteredResults = this._filteredResults() return ( <div className={`row column expanded`}> <div className={`show-for-large large-3 columns`}> { Object.keys(this.props.facetsTreeData).length && <Facets facets = {this._prepareFacetTreeData(filteredResults)} setChecked = {this._setChecked} /> } </div> <div className={`small-12 large-9 columns`}> <ReactTooltipStyleClass /> { this.props.results && this.props.results.length && <Results results = {filteredResults} atlasUrl = {this.props.atlasUrl} {...this.props.legend} /> } </div> </div> ) } } DifferentialRouter.propTypes = { facetsTreeData: PropTypes.array, results: PropTypes.array, legend: PropTypes.object, atlasUrl: PropTypes.string.isRequired, } export default DifferentialRouter
react/features/e2ee/components/E2EELabel.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { translate } from '../../base/i18n'; import { IconE2EE } from '../../base/icons'; import { Label } from '../../base/label'; import { COLORS } from '../../base/label/constants'; import { connect } from '../../base/redux'; import { Tooltip } from '../../base/tooltip'; import { _mapStateToProps, type Props } from './AbstractE2EELabel'; /** * React {@code Component} for displaying a label when everyone has E2EE enabled in a conferene. * * @augments Component */ class E2EELabel extends Component<Props> { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { if (!this.props._showLabel) { return null; } const { _e2eeLabels, t } = this.props; const content = _e2eeLabels?.labelToolTip || t('e2ee.labelToolTip'); return ( <Tooltip content = { content } position = { 'bottom' }> <Label color = { COLORS.green } icon = { IconE2EE } /> </Tooltip> ); } } export default translate(connect(_mapStateToProps)(E2EELabel));
app/components/common/List.js
ariel-zplinux/data-extractor-mern
import React from 'react'; export default class List extends React.Component { render() { const ItemType = this.props.itemType; const items = this.props.items || []; const markupItems = this.createItemsMarkup(items, ItemType); return (<ul className="ui-list">{markupItems}</ul>); } createItemsMarkup(items, Type) { const markupItems = items.map((item) => { return ( <li className="ui-list-item" key={item.name}> <Type data={item}/> </li> ); }); return markupItems; } }
myblog/src/components/MessageOptionNav/messageOptionNav.js
wuwzhang/koa2-react-blog-wuw
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchs as messageFetch, actions as messageAction } from '../Contact/' import { Popconfirm, message } from 'antd'; import { FormattedMessage } from 'react-intl'; class MessageOptionNav extends Component { constructor(props) { super(props); this.state = { alertVisble: false } this._deleteMessage = this._deleteMessage.bind(this); this._checkMessage = this._checkMessage.bind(this); this.cancelDelete = this.cancelDelete.bind(this); this.confirmDelete = this.confirmDelete.bind(this); this.cancelCheck = this.cancelCheck.bind(this); this.confirmCheck = this.confirmCheck.bind(this); } async _deleteMessage(event) { event.preventDefault(); let result = await messageFetch.deleteMessage(this.props.id); if (result.code === '1') { this.props.deleteMessage(this.props.index, this.props.isChecked); message.success('Delete the message'); } else { message.error('Failure'); } } async _checkMessage(event) { event.preventDefault(); let result = await messageFetch.changeMessageCheck(this.props.id); if (result.code === '1') { this.props.setMessageChecked(this.props.index); message.success('Checked the message'); } else { message.error('Failure'); } } confirmDelete (e) { e.preventDefault(); this._deleteMessage(e); } cancelDelete (e) { e.preventDefault(); message.error('Cancle delete'); } confirmCheck (e) { e.preventDefault(); this._checkMessage(e); } cancelCheck (e) { e.preventDefault(); message.error('Cancle check'); } render() { let { myStyle = {color: '#FF7E67'}, isChecked } = this.props; return ( <nav className="article-option-nav"> <ul> <li> <Popconfirm title="Are you sure delete this task?" onConfirm={this.confirmDelete} onCancel={this.cancelDelete} okText="Yes" cancelText="No" > <span style = { myStyle }> <FormattedMessage id="Delete" defaultMessage="Delete" /> </span> </Popconfirm> </li> <li> { isChecked ? <span className='comment-checked'> <FormattedMessage id="Checked" defaultMessage="Checked" /> </span> : <span> <Popconfirm title="Are you sure checked this task?" onConfirm={this.confirmCheck} onCancel={this.cancelCheck} okText="Yes" cancelText="No" > <span style = { myStyle }> <FormattedMessage id="Check" defaultMessage="Check" /> </span> </Popconfirm> </span> } </li> </ul> </nav> ); } } const mapDispatchToProps = (dispatch) => { return { deleteMessage: (index, checked) => { dispatch(messageAction.messageDelete(index, checked)); }, setMessageChecked: (index) => { dispatch(messageAction.messageChecked(index)); } } } export default connect(null, mapDispatchToProps)(MessageOptionNav);
src/static/containers/Login/index.js
Seedstars/django-react-redux-base
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import classNames from 'classnames'; import { push } from 'react-router-redux'; import t from 'tcomb-form'; import PropTypes from 'prop-types'; import * as actionCreators from '../../actions/auth'; const Form = t.form.Form; const Login = t.struct({ email: t.String, password: t.String }); const LoginFormOptions = { auto: 'placeholders', help: <i>Hint: a@a.com / qw</i>, fields: { password: { type: 'password' } } }; class LoginView extends React.Component { static propTypes = { dispatch: PropTypes.func.isRequired, isAuthenticated: PropTypes.bool.isRequired, isAuthenticating: PropTypes.bool.isRequired, statusText: PropTypes.string, actions: PropTypes.shape({ authLoginUser: PropTypes.func.isRequired }).isRequired, location: PropTypes.shape({ search: PropTypes.string.isRequired }) }; static defaultProps = { statusText: '', location: null }; constructor(props) { super(props); const redirectRoute = this.props.location ? this.extractRedirect(this.props.location.search) || '/' : '/'; this.state = { formValues: { email: '', password: '' }, redirectTo: redirectRoute }; } componentWillMount() { if (this.props.isAuthenticated) { this.props.dispatch(push('/')); } } onFormChange = (value) => { this.setState({ formValues: value }); }; extractRedirect = (string) => { const match = string.match(/next=(.*)/); return match ? match[1] : '/'; }; login = (e) => { e.preventDefault(); const value = this.loginForm.getValue(); if (value) { this.props.actions.authLoginUser(value.email, value.password, this.state.redirectTo); } }; render() { let statusText = null; if (this.props.statusText) { const statusTextClassNames = classNames({ 'alert': true, 'alert-danger': this.props.statusText.indexOf('Authentication Error') === 0, 'alert-success': this.props.statusText.indexOf('Authentication Error') !== 0 }); statusText = ( <div className="row"> <div className="col-sm-12"> <div className={statusTextClassNames}> {this.props.statusText} </div> </div> </div> ); } return ( <div className="container login"> <h1 className="text-center">Login</h1> <div className="login-container margin-top-medium"> {statusText} <form onSubmit={this.login}> <Form ref={(ref) => { this.loginForm = ref; }} type={Login} options={LoginFormOptions} value={this.state.formValues} onChange={this.onFormChange} /> <button disabled={this.props.isAuthenticating} type="submit" className="btn btn-default btn-block" > Submit </button> </form> </div> </div> ); } } const mapStateToProps = (state) => { return { isAuthenticated: state.auth.isAuthenticated, isAuthenticating: state.auth.isAuthenticating, statusText: state.auth.statusText }; }; const mapDispatchToProps = (dispatch) => { return { dispatch, actions: bindActionCreators(actionCreators, dispatch) }; }; export default connect(mapStateToProps, mapDispatchToProps)(LoginView); export { LoginView as LoginViewNotConnected };
app/config/routes.js
giojavi04/react-webpack-init
import React from 'react' import { Router, Route, hashHistory, IndexRoute } from 'react-router' import Main from '../components/Main' import Home from '../components/Home' import PromptContainer from '../containers/PromptContainer' import ConfirmBattleContainer from '../containers/ConfirmBattleContainer' import ResultsContainer from '../containers/ResultsContainer' const routes = ( <Router history={hashHistory}> <Route path='/' component={Main}> <IndexRoute component={Home} /> <Route path='playerOne' header='Player One' component={PromptContainer} /> <Route path='playerTwo/:playerOne' header='Player Two' component={PromptContainer} /> <Route path='battle' component={ConfirmBattleContainer} /> <Route path='results' component={ResultsContainer} /> </Route> </Router> ); export default routes
rallyboard-v1/src/server.js
tylerjw/rallyscores
"use strict"; import path from 'path'; import http from 'http'; import Express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import routes from './routes'; import NotFoundPage from './components/NotFoundPage'; import SocketIO from 'socket.io'; import { MongoClient } from 'mongodb'; // Initalize the server and configure support for ejs templates const app = new Express(); const server = new http.Server(app); const io = new SocketIO(server); const port = process.env.PORT || 3000; const env = process.env.NODE_ENV || 'production'; const mongo_url = 'mongodb://localhost:27017/rally' const mongo = MongoClient() app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // devind the folder that will be used for static assets app.use(Express.static(path.join(__dirname, 'static'))); let updateEventsData = () => { try { mongo.connect(mongo_url, (err, db) => { if (err) { console.log('Unable to connect to database server', err); } else { let collection = db.collection('ra_events'); let results = collection.find({},{'sort': ['start':'decending']}); results.toArray((err, data) => { if (err) { console.log('Unable to get events from database', err); } else if (data) { let parentEvents = {}; let years = new Set(); for (let event of data) { if (event['type'] === 'parent') { if (event.year in parentEvents) { if (is_live(event)) { event['live'] = 'LIVE event' } parentEvents[event.year].push(event) } else { parentEvents[event.year] = [event] } years.add(event.year) } } years = Array.from(years).sort(function(a, b){return b-a}); events_data = { "events": parentEvents, "years": years }; } }) } }); } catch (e) { console.log('exception thrown by mongo.connect', e); } } // events data for main page let events_data; app.get('/events.json', (req, res) => { if (!events_data) { console.log('updating events data') updateEventsData(); } res.send(events_data); }); // universal routing and rendering app.get('*', (req, res) => { match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { // in case of error display the error message if (err) { return res.status(500).send(err.message); } // in case of redirect propagate the redirect to the browser if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } // generate the React markup for the current route let markup; if (renderProps) { // if the current route matched we have renderProps markup = renderToString(<RouterContext {...renderProps}/>); } else { // otherwise we can render a 404 page markup = renderToString(<NotFoundPage/>); res.status(404); } // render the index template with the embedded react markup return res.render('index', { markup }); } ); }); // socket io let sockets = {}; io.on('connection', (socket) => { console.log('socket connected'); sockets[socket.id] = socket; socket.on('disconnect', () => { console.log('socket disconnected'); }); }); // start the server server.listen(port, err => { if (err) { return console.error(err); } console.info(`Server running on http://localhost:${port} [${env}]`); });
src/svg-icons/action/trending-down.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingDown = (props) => ( <SvgIcon {...props}> <path d="M16 18l2.29-2.29-4.88-4.88-4 4L2 7.41 3.41 6l6 6 4-4 6.3 6.29L22 12v6z"/> </SvgIcon> ); ActionTrendingDown = pure(ActionTrendingDown); ActionTrendingDown.displayName = 'ActionTrendingDown'; ActionTrendingDown.muiName = 'SvgIcon'; export default ActionTrendingDown;
src/js/index.js
dupengdl/kickoffredux
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/app'; import configureStore from './store/configureStore'; import '../sass/index.scss'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('container') );
app/components/FileSystem.js
FermORG/FermionJS
import React, { Component } from 'react'; import { SortableTreeWithoutDndContext } from './src/index'; // 'react-sortable-tree'; import { connect } from 'react-redux'; import styles from './photon.scss'; import coreStyles from './Core.scss'; const path = require('path'); const dirTree = require('directory-tree'); class FileTree extends Component { constructor(props) { super(props); this.state = { treeData: this.getInitial() }; this.getInitial = this.getInitial.bind(this); this.getUpdate = this.getUpdate.bind(this); this.handleClick = this.handleClick.bind(this); } // for flow props: { workspace: {}, setActiveComponent: ()=> void, }; getUpdate() { this.setState({ treeData: this.getInitial() }); } componentDidUpdate() { const newData = this.getInitial(); const oldData = this.state.treeData; if (newData[0].children.length !== oldData[0].children.length) { this.getUpdate(); } } getInitial() { const treeStructure = this.props.workspace.components.workspace; const treeComponents = this.props.workspace.components; const treeData = [getTreeData(treeStructure)]; function getTreeData(workspaceTree) { return { title: 'app', children: getChildrenData(workspaceTree.children), expanded: true, id: '0', }; } function getChildrenData(childrenArray) { const childrenArrayFinal = []; for (let i = 0; i < childrenArray.length; i++) { const currComponent = treeComponents[childrenArray[i]]; const currComponentChildren = currComponent.children; if (currComponentChildren.length !== 0) { childrenArrayFinal.push({ title: currComponent.name, children: getChildrenData(currComponentChildren), expanded: true, id: currComponent.id, }); } else { childrenArrayFinal.push({ title: currComponent.name, expanded: true, id: currComponent.id, }); } } return childrenArrayFinal; } return treeData; } // changes activeComponent handleClick(e, component) { this.props.setActiveComponent(component); let initial = e.target.innerHTML; e.target.innerHTML = `<span style="color:green">${initial}</span>`; } render() { const getData = this.props.workspace; return ( <div style={{ height: '100%' }}> <SortableTreeWithoutDndContext treeDataRedux={getData} treeData={this.state.treeData} canDrag={false} onChange={(treeDataRedux) => this.setState({ treeData: treeDataRedux })} handleClick={this.handleClick} /> </div> ); } } function mapStateToProps(state) { return { workspace: state.workspace }; } export default connect(mapStateToProps)(FileTree);
app/react-icons/fa/hourglass.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaHourglass extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m36.6 35.7q0.3 0 0.5 0.2t0.2 0.5v2.9q0 0.3-0.2 0.5t-0.5 0.2h-32.9q-0.3 0-0.5-0.2t-0.2-0.5v-2.9q0-0.3 0.2-0.5t0.5-0.2h32.9z m-30.7-1.4q0.1-1.2 0.4-2.4t0.6-2.1 1.1-2 1.2-1.7 1.4-1.5 1.5-1.4 1.5-1.2 1.5-1 1.5-1q-1-0.6-1.5-1t-1.5-1-1.5-1.2-1.5-1.4-1.4-1.5-1.2-1.7-1.1-2-0.6-2.1-0.4-2.4h28.5q-0.1 1.2-0.4 2.4t-0.6 2.1-1.1 2-1.2 1.7-1.4 1.5-1.5 1.4-1.6 1.2-1.4 1-1.5 1q1 0.6 1.5 1t1.4 1 1.6 1.3 1.5 1.3 1.4 1.5 1.2 1.7 1.1 2 0.6 2.1 0.4 2.4h-28.5z m30.7-34.3q0.3 0 0.5 0.2t0.2 0.5v2.9q0 0.3-0.2 0.5t-0.5 0.2h-32.9q-0.3 0-0.5-0.2t-0.2-0.5v-2.9q0-0.3 0.2-0.5t0.5-0.2h32.9z"/></g> </IconBase> ); } }
scripts/stores/SearchBookStore.js
nverdhan/satticentre
import React from 'react'; import { register } from '../AppDispatcher'; import { createStore, mergeIntoBag, isInBag } from '../utils/StoreUtils'; import selectn from 'selectn'; const listBooks = [] // For Pagination, e.g. say In one Chuck 10 books are loaded const _books = {} const srchData = { pageNo : 1, srchString : '' } const endOfResultsOptions = { showLoading : false, endOfResults : false, } const SearchBookStore = createStore({ get(){ return _books; }, // updateBooksFromGoogle(books){ // this.cleanBookList(); // var x = (Object.keys(books)).length; // if(x == 0){ // n = 40 // }else{ // var n = Math.min(20, books.length); // } // for(var i = 0; i < n; i++){ // var id = books[i]['id']; // _books[id] = books[i]['volumeInfo']; // } // }, updateBooksFromGR(books){ if(this.getPageNo() == 1){ this.cleanBookList() } for (var i = books.length - 1; i >= 0; i--) { var id = books[i]['best_book']['id']['$t']; var book = { title : books[i]['best_book']['title'], image : books[i]['best_book']['image_url'], rating : books[i]['best_book']['average_rating'], author : books[i]['best_book']['author']['name'], } _books[id] = book; } }, updateEndOfResultsOption(showLoading, endOfResults){ endOfResultsOptions['showLoading'] = showLoading; endOfResultsOptions['endOfResults'] = endOfResults; }, updateSrchData(pageNo, string){ srchData['pageNo'] = pageNo; srchData['srchString'] = string; }, showLoading(){ return endOfResultsOptions['showLoading']; }, endOfResults(){ return endOfResultsOptions['endOfResults']; }, getPageNo(){ return srchData['pageNo']; }, getSrchString(){ return srchData['srchString']; }, cleanBookList(){ for(var key in _books){ delete _books[key]; } } }); SearchBookStore.dispathToken = register(action=>{ const responseBook = selectn('response.data', action); switch(action.type){ case 'FETCH_BOOKS_FROM_API': SearchBookStore.updateEndOfResultsOption(true, false) break; case 'FETCH_BOOKS_FROM_API_SUCCESS': if(responseBook){ var showLoading = false; var endOfResults = false var responseBookObj = JSON.parse(responseBook); var resultsBook = responseBookObj.GoodreadsResponse.search.results.work; var pageNo = Math.floor(responseBookObj.GoodreadsResponse.search['results-end']/20); var srchString = responseBookObj.GoodreadsResponse.search.query; if(responseBookObj.GoodreadsResponse.search['results-end'] == responseBookObj.GoodreadsResponse.search['total-results']){ endOfResults = true; } SearchBookStore.updateEndOfResultsOption(showLoading, endOfResults) SearchBookStore.updateSrchData(pageNo, srchString); SearchBookStore.updateBooksFromGR(resultsBook); } break; } SearchBookStore.emitChange(); }); export default SearchBookStore;
src/main/index.js
liaofeijun/feijun
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/index.js
anagrius/robocode
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('root'));
client/modules/App/components/TalentInput/PerformerSelect.js
aksm/refactored-palm-tree
import React from 'react'; import styles from '../../TalentInput.css'; import { Button } from 'react-bootstrap'; class PerformerSelect extends React.Component { constructor(props) { super(props); this.state = { type: '', option: 'comedian' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { this.setState({ option: e.target.value }); console.log(this.state); } handleSubmit(e) { e.preventDefault(); let input = { type: this.state.option }; this.props.setField(input); // console.log(this.state.name); } render() { return ( <div className={styles.container+' '+styles.styleForToggle} id="type1"> <h2>What type of performer are you? Please select one.</h2> <form onSubmit={this.handleSubmit} > <input type="radio" name="performer" value="comedian" checked={this.state.option === 'comedian'} onChange={this.handleChange} /> <span>Comedian</span> <br /> <input type="radio" name="performer" value="musician" checked={this.state.option === 'musician'} onChange={this.handleChange} /> <span>Musician</span> <br /> <input type="radio" name="performer" value="poet" checked={this.state.option === 'poet'} onChange={this.handleChange} /> <span>Poet</span> <br /> <br /> <Button type="submit" id="submit2">Submit</Button> </form> </div> ) } } module.exports = PerformerSelect;