path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/SettingsPage.js
guilhermehn/all-mangas-reader
import React from 'react' import SettingsStore from '../stores/SettingsStore' import SettingsAPI from '../apis/SettingsAPI' import { SETTINGS_SECTIONS } from '../constants/SettingsConstants' import SettingsHolder from './settings/SettingsHolder' import MigrationNotice from './settings/MigrationNotice' import SettingsContent from './settings/SettingsContent' function getStateFromStores() { return { settings: SettingsStore.getSettings() } } function dismissMigration() { SettingsAPI.setOption('dismissMigration', true) } const SettingsPage = React.createClass({ getInitialState() { return getStateFromStores() }, componentDidMount() { SettingsAPI.loadSettings() SettingsStore.addChangeListener(this._onChange) }, componentWillUnmount() { SettingsStore.removeChangeListener(this._onChange) }, _onChange() { this.setState(getStateFromStores()) }, componentDidUpdate() { // When changing the sync option, the user // must be remembered about migrating the // old data if not already migrated }, getSettingsValue(key) { return this.state.settings[key] }, render() { let settings = this.state.settings if (Object.keys(settings).length === 0) { // This should return a loader view return ( <SettingsHolder> <h3>Loading settings...</h3> </SettingsHolder> ) } let shouldShowMigrationNotice = settings.syncData && !settings.dismissMigration return ( <SettingsHolder> { shouldShowMigrationNotice && <MigrationNotice onDismiss={ dismissMigration } /> } <SettingsContent sections={ SETTINGS_SECTIONS } settings={ settings } /> </SettingsHolder> ) } }) export default SettingsPage
services/web/src/index.js
ojedarob/tennis-buddy
import React from 'react' import { render } from 'react-dom' import { createStore, dispatch, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import logger from 'redux-logger' import { Provider } from 'react-redux' import App from './containers/App' import reducer from './reducers/reducer' const middleware = [ thunk, logger ] const store = createStore(reducer, applyMiddleware(...middleware)) render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/containers/Accounts/ResetPassword/Complete/index.js
westoncolemanl/tabbr-web
import React from 'react' import Link from 'react-router-dom/Link' import Card, { CardActions, CardContent } from 'material-ui/Card' import Typography from 'material-ui/Typography' import Button from 'material-ui/Button' import { CardLogoHeader } from 'components' export default () => <Card raised > <CardLogoHeader /> <CardContent> <Typography variant={'headline'} gutterBottom > {'Password reset complete'} </Typography> </CardContent> <CardActions className={'flex flex-row justify-end'} > <Button component={Link} to={'/accounts/sign-in'} children={'NEXT'} color={'primary'} variant={'raised'} /> </CardActions> </Card>
examples/js/app.js
echaouchna/react-bootstrap-tab
import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { IndexRoute, Router, Route, hashHistory } from 'react-router'; import App from './components/App'; import Home from './components/Home'; import GettingStarted from './components/GettingStarted'; import PageNotFound from './components/PageNotFound'; import Basic from './basic/demo'; import Column from './column/demo'; import Sort from './sort/demo'; import ColumnFormat from './column-format/demo'; import ColumnFilter from './column-filter/demo'; import Selection from './selection/demo'; import Pagination from './pagination/demo'; import Manipulation from './manipulation/demo'; import CellEdit from './cell-edit/demo'; import Style from './style/demo'; import Advance from './advance/demo'; import Other from './others/demo'; import Complex from './complex/demo'; import Remote from './remote/demo'; import Expand from './expandRow/demo'; import Custom from './custom/demo'; import Span from './column-header-span/demo'; import KeyBoardNav from './keyboard-nav/demo'; const renderApp = () => { ReactDOM.render( <AppContainer> <Router history={ hashHistory }> <Route path='/' component={ App }> <IndexRoute component={ Home } /> <Route path='getting-started' component={ GettingStarted }/> <Route path='examples'> <Route path='basic' component={ Basic } /> <Route path='column' component={ Column } /> <Route path='sort' component={ Sort } /> <Route path='column-format' component={ ColumnFormat } /> <Route path='column-filter' component={ ColumnFilter } /> <Route path='column-header-span' component={ Span } /> <Route path='selection' component={ Selection } /> <Route path='pagination' component={ Pagination } /> <Route path='manipulation' component={ Manipulation } /> <Route path='cell-edit' component={ CellEdit } /> <Route path='style' component={ Style } /> <Route path='advance' component={ Advance } /> <Route path='others' component={ Other } /> <Route path='complex' component={ Complex } /> <Route path='remote' component={ Remote } /> <Route path='custom' component={ Custom } /> <Route path='expandRow' component={ Expand } /> <Route path='keyboard-nav' component={ KeyBoardNav } /> </Route> <Route path='*' component={ PageNotFound }/> </Route> </Router> </AppContainer>, document.querySelector('#root')); }; if (module.hot) { module.hot.accept('./app', renderApp); } renderApp();
app/javascript/mastodon/components/status_content.js
Arukas/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { isRtl } from '../rtl'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${mention.get('id')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, '').toLowerCase(); if (this.context.router && e.button === 0) { e.preventDefault(); this.context.router.history.push(`/timelines/tag/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) { return; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const directionStyle = { direction: 'ltr' }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, 'status__content--with-spoiler': status.get('spoiler_text').length > 0, }); if (isRtl(status.get('search_index'))) { directionStyle.direction = 'rtl'; } if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} /> {' '} <button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} /> </div> ); } else if (this.props.onClick) { return ( <div ref={this.setRef} tabIndex='0' className={classNames} style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} dangerouslySetInnerHTML={content} /> ); } else { return ( <div tabIndex='0' ref={this.setRef} className='status__content' style={directionStyle} dangerouslySetInnerHTML={content} /> ); } } }
client/src/MyJobsButton.js
roxroy/codeploy
import React, { Component } from 'react'; class MyJobsButton extends Component { constructor(props) { super(props); this.viewJobs = this.viewJobs.bind(this); } viewJobs() { this.props.closeResourceModal(); this.props.viewJobs(); } render(){ return( <div> <button className="modal-button" onClick={this.viewJobs}>My Jobs</button> </div> ); } } module.exports = MyJobsButton;
src/templates/category-template.js
wall3/wall3.github.io
// @flow strict import React from 'react'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import Sidebar from '../components/Sidebar'; import Feed from '../components/Feed'; import Page from '../components/Page'; import Pagination from '../components/Pagination'; import { useSiteMetadata } from '../hooks'; import type { PageContext, AllMarkdownRemark } from '../types'; type Props = { data: AllMarkdownRemark, pageContext: PageContext }; const CategoryTemplate = ({ data, pageContext }: Props) => { const { title: siteTitle, subtitle: siteSubtitle } = useSiteMetadata(); const { category, currentPage, prevPagePath, nextPagePath, hasPrevPage, hasNextPage, } = pageContext; const { edges } = data.allMarkdownRemark; const pageTitle = currentPage > 0 ? `${category} - Page ${currentPage} - ${siteTitle}` : `${category} - ${siteTitle}`; return ( <Layout title={pageTitle} description={siteSubtitle}> <Sidebar /> <Page title={category}> <Feed edges={edges} /> <Pagination prevPagePath={prevPagePath} nextPagePath={nextPagePath} hasPrevPage={hasPrevPage} hasNextPage={hasNextPage} /> </Page> </Layout> ); }; export const query = graphql` query CategoryPage($category: String, $postsLimit: Int!, $postsOffset: Int!) { allMarkdownRemark( limit: $postsLimit, skip: $postsOffset, filter: { frontmatter: { category: { eq: $category }, template: { eq: "post" }, draft: { ne: true } } }, sort: { order: DESC, fields: [frontmatter___date] } ){ edges { node { fields { categorySlug slug } frontmatter { date description category title } } } } } `; export default CategoryTemplate;
src/controls/filefield/preview.js
thinktopography/reframe
import ImageFileToken from './image_file_token' import PlainFileToken from './plain_file_token' import PropTypes from 'prop-types' import React from 'react' import qs from 'qs' class Preview extends React.Component { static propTypes = { file: PropTypes.object, preview: PropTypes.string, onRemove: PropTypes.func } render() { const dpis = [1,2] const { file } = this.props const content_type = file.contentType || file.asset.content_type const isImage = (content_type.split('/')[0] === 'image') const type = isImage ? 'image' : 'plain' return ( <div className={`reframe-filefield-token ${type}`}> { file.status === 'added' && <div className="reframe-filefield-progress"> <div className="ui green progress"> <div className="bar" style={{ width: 0 }} /> </div> </div> } { file.status === 'uploading' && <div className="reframe-filefield-progress"> <div className="ui green progress"> <div className="bar" style={{ width: `${file.progress}%`}}> <div className="progress">{ file.progress }%</div> </div> </div> </div> } <div className="reframe-filefield-remove" onClick={ this._handleRemove.bind(this) }> { isImage ? <i className="fa fa-fw fa-times-circle" /> : <i className="fa fa-fw fa-times" /> } </div> { isImage ? <ImageFileToken { ...this._getImageFile() } /> : <PlainFileToken { ...this._getPlainFile() } /> } </div> ) } _getImageFile() { const { file, preview } = this.props return { file: file.asset, preview } } _getPlainFile() { const { file } = this.props const file_name = file.fileName || file.asset.file_name const file_size = file.fileSize || file.asset.file_size return { file_name, file_size } } _handleRemove() { this.props.onRemove() } } export default Preview
addons/info/src/components/types/InstanceOf.js
rhalff/storybook
import React from 'react'; import { TypeInfo, getPropTypes } from './proptypes'; const InstanceOf = ({ propType }) => <span>{getPropTypes(propType)}</span>; InstanceOf.propTypes = { propType: TypeInfo.isRequired, }; export default InstanceOf;
app/jsx/new_user_tutorial/ConfirmEndTutorialDialog.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import I18n from 'i18n!new_user_tutorial' import {Button} from '@instructure/ui-buttons' import Modal from '../shared/components/InstuiModal' import axios from 'axios' const API_URL = '/api/v1/users/self/features/flags/new_user_tutorial_on_off' export default function ConfirmEndTutorialDialog({isOpen, handleRequestClose}) { return ( <Modal open={isOpen} size="small" onDismiss={handleRequestClose} label={I18n.t('End Course Set-up Tutorial')} > <Modal.Body> {I18n.t( 'Turning off this tutorial will remove the tutorial tray from your view for all of your courses. It can be turned back on under Feature Options in your User Settings.' )} </Modal.Body> <Modal.Footer> <Button onClick={handleRequestClose}>{I18n.t('Cancel')}</Button> &nbsp; <Button onClick={() => axios.put(API_URL, {state: 'off'}).then(() => ConfirmEndTutorialDialog.onSuccess()) } variant="primary" > {I18n.t('Okay')} </Button> </Modal.Footer> </Modal> ) } ConfirmEndTutorialDialog.onSuccess = () => window.location.reload() ConfirmEndTutorialDialog.propTypes = { isOpen: PropTypes.bool, handleRequestClose: PropTypes.func.isRequired } ConfirmEndTutorialDialog.defaultProps = { isOpen: false }
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
UKForeignOffice/ETD-prototype-upload
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
app/components/Options-bar.js
L-A/Little-Jekyll
import React, { Component } from 'react'; import Dispatcher from '../utils/front-end-dispatcher'; import SimpleButton from './simple-button' var OptionsBar = React.createClass({ requestNewSite: function() { Dispatcher.send('addSite'); }, createNewSite: function() { Dispatcher.send('createSite'); }, render: function () { return ( <div className="options-bar"> <SimpleButton onClick={this.createNewSite} className="btn-create" hintText="Create a new template site" /> <span className={this.props.hintAvailable ? "hint-text hint-available" : "hint-text"}>{this.props.hintText}</span> <SimpleButton href="#" onClick={this.requestNewSite} className="btn-open" hintText="Open an existing Jekyll site" /> {/* <SimpleButton className="btn-settings" /> */} </div> ); } }) module.exports = OptionsBar;
winearb/static/react/js/articles.js
REBradley/WineArb
import React from 'react'; import ReactDOM from 'react-dom'; import Col from 'react-bootstrap/lib/Col'; import Jumbotron from 'react-bootstrap/lib/Jumbotron'; import Image from 'react-bootstrap/lib/Image'; import Button from 'react-bootstrap/lib/Button'; import ButtonGroup from 'react-bootstrap/lib/ButtonGroup'; import Fade from 'react-bootstrap/lib/Fade'; import Title from "./components/title.js"; import { Username } from "./components/username.js"; import { Date } from "./components/date.js"; import Text from "./components/text.js"; import InnerHTML from "./components/innerhtml.js"; function CustomJTron(ShowWrappedComponent, ToggleWrappedComponent) { return class FadeInJumbotronIvory extends React.Component { constructor(props) { super(props); this.state = {isClicked: false}; this.handleClick = this.handleClick.bind(this); } handleClick () { this.setState(prevState => ({ isClicked: !prevState.isClicked })); } render() { const isClicked = this.state.isClicked; return( <Col> <div> <Jumbotron style={{backgroundColor: '#FFFFF0', float: 'center', padding: 'none', border: 'outset black'}}> <div className="JumbotronItem" style={{textAlign: 'center'}}> <div> <ShowWrappedComponent {...this.props} /> </div> <ButtonGroup vertical block> <Col md={6} mdOffset={3}> <Button bsSize="xsmall" onClick={this.handleClick}> {isClicked ? 'Close' : 'View Content'} </Button> </Col> </ButtonGroup> </div> </Jumbotron> </div> <div> <Fade in={isClicked} unmountOnExit={true} timeout={1000}> <Jumbotron style={{backgroundColor: '#FFFFF0', float: 'center', padding: 'none', border: 'outset black', marginTop: '0px'}}> <div className="JumbotronItem" style={{textAlign: 'center'}}> <div> {this.props.children} <ToggleWrappedComponent {...this.props} /> </div> </div> </Jumbotron> </Fade> </div> </Col> ); } } }; const ArticleHeading = (props) => { return( <div> <Image style={{ display: 'inline-block' }}src={props.image} responsive /> <Title main_title={props.main_title} sub_title={props.sub_title} /> <Username username={props.author} /> <Date date={props.date} /> </div> ); }; const Article = CustomJTron(ArticleHeading, InnerHTML); export { Article, CustomJTron };
src/main.js
dontexpectanythingsensible/password-checker
import React from 'react'; import ReactDOM from 'react-dom'; import createStore from './store/createStore'; import AppContainer from './containers/AppContainer'; import * as OfflinePluginRuntime from 'offline-plugin/runtime'; OfflinePluginRuntime.install(); // ======================================================== // Store Instantiation // ======================================================== const initialState = window.___INITIAL_STATE__; const store = createStore(initialState); // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root'); let render = () => { const routes = require('./routes/index').default(store); ReactDOM.render( <AppContainer store={ store } routes={ routes } />, MOUNT_NODE ); }; // This code is excluded from production bundle if (__DEV__) { if (module.hot) { // Development render functions const renderApp = render; const renderError = (error) => { const RedBox = require('redbox-react').default; ReactDOM.render(<RedBox error={ error } />, MOUNT_NODE); }; // Wrap render in try/catch render = () => { try { renderApp(); } catch (error) { console.error(error); renderError(error); } }; // Setup hot module replacement module.hot.accept('./routes/index', () => setImmediate(() => { ReactDOM.unmountComponentAtNode(MOUNT_NODE); render(); }) ); } } // ======================================================== // Go! // ======================================================== render();
client/src/universal/routes/async.js
mariocoski/express-typescript-react-redux-universal
import React from 'react'; import Loadable from 'react-loadable'; function loadAsync(loader){ return Loadable({ loader, loading: ()=>(<div>Loading...</div>) }); } export const Home = loadAsync(() => import('universal/containers/pages/HomeContainer.jsx')); export const Todos = loadAsync(() => import('universal/containers/pages/TodosContainer.jsx')); export const NotFound = loadAsync(() => import('universal/containers/pages/NotFoundContainer.jsx')); export const Login = loadAsync(() => import('universal/containers/auth/LoginContainer.jsx')); export const Register = loadAsync(() => import('universal/containers/auth/RegistrationContainer.jsx')); export const Dashboard = loadAsync(() => import('universal/containers/dashboard/DashboardContainer.jsx'));
app/jsx/courses/ModulesHomePage.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import {IconModuleSolid, IconUploadLine} from '@instructure/ui-icons' import I18n from 'i18n!modules_home_page' export default class ModulesHomePage extends React.Component { static propTypes = { onCreateButtonClick: PropTypes.func } static defaultProps = { onCreateButtonClick: () => {} } render() { const importURL = window.ENV.CONTEXT_URL_ROOT + '/content_migrations' return ( <ul className="ic-EmptyStateList"> <li className="ic-EmptyStateList__Item"> <div className="ic-EmptyStateList__BillboardWrapper"> <button type="button" className="ic-EmptyStateButton" onClick={this.props.onCreateButtonClick} > <IconModuleSolid className="ic-EmptyStateButton__SVG" /> <span className="ic-EmptyStateButton__Text">{I18n.t('Create a new Module')}</span> </button> </div> </li> <li className="ic-EmptyStateList__Item"> <div className="ic-EmptyStateList__BillboardWrapper"> <a href={importURL} className="ic-EmptyStateButton"> <IconUploadLine className="ic-EmptyStateButton__SVG" /> <span className="ic-EmptyStateButton__Text">{I18n.t('Add existing content')}</span> </a> </div> </li> </ul> ) } }
src/pwa.js
tpphu/react-pwa
import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from './helpers/Html'; export default function () { return `<!doctype html>${ReactDOM.renderToStaticMarkup(<Html />)}`; }
demo/components/switch/PagerOptions.js
ctco/rosemary-ui
import React from 'react'; import OptionsTable from '../../helper/OptionsTable'; import {MonthPager, Pager} from '../../../src'; export default () => { let propDescription = { onPrevBtnClick: { values: 'function', description: 'Is called when a left btn is clicked' }, onNextBtnClick: { values: 'function', description: 'Is called when a right btn is clicked' }, value: { values: 'any', description: 'value will be displayed' }, prevBtnIcon: { values: 'string', description: 'icon name' }, nextBtnIcon: { values: 'string', description: 'icon name' } }; return ( <div> <h2>Pager</h2> <OptionsTable component={Pager} propDescription={propDescription}/> <br/> <h2>MonthPager</h2> <OptionsTable component={MonthPager} propDescription={propDescription}/> </div> ); };
examples/huge-apps/routes/Messages/components/Messages.js
jamiehill/react-router
import React from 'react'; class Messages extends React.Component { render () { return ( <div> <h2>Messages</h2> </div> ); } } export default Messages;
scripts/components/pages/home/login.js
evilfaust/lyceum9sass
import React from 'react'; const request = require('superagent'); class Login extends React.Component { constructor(props) { super(props); this.render = this.render.bind(this); this.loginChange = this.loginChange.bind(this); this.sendLogin = this.sendLogin.bind(this); this.values = {}; } loginChange(e) { this.values[e.target.id] = e.target.value; console.log(this.values); this.login = this.values.login; this.password = this.values.password; this.email = this.values.email; } sendLogin(e) { e.preventDefault(); console.log(this.values); request .post('http://localhost:8080/add/user') .withCredentials() .send({ login: this.login }) .send({ password: this.password }) .send({ email: this.email }) .end(); } render() { return ( <div className="login"> <form> <div className="title-login">Registration form</div> <div className="login-item"> <i className="icon fa fa-user fa-2x"></i> <input className="login-input" id="login" placeholder="Enter login" onChange={this.loginChange} /> </div> <br /> <div className="login-item"> <i className="icon fa fa-lock fa-2x"></i> <input className="login-input" id="password" placeholder="Enter password" type="password" onChange={this.loginChange} /> </div> <br /> <div className="login-item"> <i className="icon fa fa-envelope-o fa-2x"></i> <input className="login-input" id="email" placeholder="Enter your e-mail" onChange={this.loginChange} /> </div> <br /> <div className="button" onClick={ this.sendLogin }>Register</div> </form> </div> ); } } export default Login;
examples/dynamic-load/routes/App.js
cycgit/dva
import React from 'react'; import { connect } from '../../../index'; import { Link } from '../../../router'; const App = ({ app }) => { const { name } = app; return ( <div> <h1>{ name }</h1> <hr/> <Link to="/profile">go to /profile</Link> </div> ); }; export default connect(({ app }) => ({ app }))(App);
src/icons/FolderSharedIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FolderSharedIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 12H24l-4-4H8c-2.21 0-3.98 1.79-3.98 4L4 36c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V16c0-2.21-1.79-4-4-4zm-10 6c2.21 0 4 1.79 4 4s-1.79 4-4 4-4-1.79-4-4 1.79-4 4-4zm8 16H22v-2c0-2.67 5.33-4 8-4s8 1.33 8 4v2z"/></svg>;} };
client/src/client/index.js
Pitzcarraldo/spring-react-redux-universal-example
import 'babel-core/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router } from 'react-router'; import { Provider } from 'react-redux'; import { ReduxRouter } from 'redux-router'; import createBrowserHistory from 'history/lib/createBrowserHistory' import configureStore from '../common/store/configureStore'; import routes from '../common/routes'; import DevTools from '../server/devtools'; import "../../styles/index.css"; const history = createBrowserHistory(); const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('root'); ReactDOM.render( <div> <Provider store={store}> <ReduxRouter> <Router children={routes} history={history} /> </ReduxRouter> </Provider> </div>, document.getElementById('root') ); if (process.env.NODE_ENV !== 'production') { require('../server/createDevToolsWindow')(store); }
examples/expo/navigation/AppNavigator.js
aksonov/react-native-router-flux
import React from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; import { StackViewStyleInterpolator } from 'react-navigation-stack'; import { Scene, Router, Actions, Reducer, ActionConst, Overlay, Tabs, Modal, Drawer, Stack, Lightbox, } from 'react-native-router-flux'; import TabBarIcon from '../components/TabBarIcon'; import MenuIcon from '../components/MenuIcon'; import DrawerContent from '../components/DrawerContent'; import HomeScreen from '../screens/HomeScreen'; import LinksScreen from '../screens/LinksScreen'; import SettingsScreen from '../screens/SettingsScreen'; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'transparent', justifyContent: 'center', alignItems: 'center', }, tabBarStyle: { backgroundColor: '#eee', }, tabBarSelectedItemStyle: { backgroundColor: '#ddd', }, }); const reducerCreate = params => { const defaultReducer = new Reducer(params); return (state, action) => { console.log('reducer: ACTION:', action); return defaultReducer(state, action); }; }; const stateHandler = (prevState, newState, action) => { console.log('onStateChange: ACTION:', action); }; const getSceneStyle = () => ({ backgroundColor: '#F5FCFF', shadowOpacity: 1, shadowRadius: 3, }); // on Android, the URI prefix typically contains a host in addition to scheme const prefix = Platform.OS === 'android' ? 'mychat://mychat/' : 'mychat://'; const transitionConfig = () => ({ screenInterpolator: StackViewStyleInterpolator.forFadeFromBottomAndroid, }); const AppNavigator = () => ( <Router createReducer={reducerCreate} onStateChange={stateHandler} getSceneStyle={getSceneStyle} uriPrefix={prefix}> <Overlay key="overlay"> <Modal key="modal" hideNavBar transitionConfig={transitionConfig}> <Lightbox key="lightbox"> <Stack key="root" hideNavBar titleStyle={{ alignSelf: 'center' }}> <Drawer hideNavBar key="drawer" onExit={() => { console.log('Drawer closed'); }} onEnter={() => { console.log('Drawer opened'); }} contentComponent={DrawerContent} drawerIcon={MenuIcon} drawerWidth={300}> <Scene hideNavBar> <Tabs key="tabbar" backToInitial onTabOnPress={() => { console.log('Back to initial and also print this'); }} swipeEnabled tabBarStyle={styles.tabBarStyle} activeBackgroundColor="white" inactiveBackgroundColor="rgba(255, 0, 0, 0.5)"> <Scene key="main_home" component={HomeScreen} title="Home" tabBarLabel="Home" icon={TabBarIcon} /> <Scene key="main_links" component={LinksScreen} title="Links" tabBarLabel="Links" icon={TabBarIcon} /> <Scene key="main_settings" component={SettingsScreen} title="Settings" tabBarLabel="Settings" icon={TabBarIcon} /> </Tabs> </Scene> </Drawer> </Stack> </Lightbox> </Modal> </Overlay> </Router> ); export default AppNavigator;
app/javascript/mastodon/components/account.js
robotstart/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import DisplayName from './display_name'; import Permalink from './permalink'; import IconButton from './icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ follow: { id: 'account.follow', defaultMessage: 'Follow' }, unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' } }); class Account extends ImmutablePureComponent { constructor (props, context) { super(props, context); this.handleFollow = this.handleFollow.bind(this); this.handleBlock = this.handleBlock.bind(this); this.handleMute = this.handleMute.bind(this); } handleFollow () { this.props.onFollow(this.props.account); } handleBlock () { this.props.onBlock(this.props.account); } handleMute () { this.props.onMute(this.props.account); } render () { const { account, me, intl } = this.props; if (!account) { return <div />; } let buttons; if (account.get('id') !== me && account.get('relationship', null) !== null) { const following = account.getIn(['relationship', 'following']); const requested = account.getIn(['relationship', 'requested']); const blocking = account.getIn(['relationship', 'blocking']); const muting = account.getIn(['relationship', 'muting']); if (requested) { buttons = <IconButton disabled={true} icon='hourglass' title={intl.formatMessage(messages.requested)} /> } else if (blocking) { buttons = <IconButton active={true} icon='unlock-alt' title={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.handleBlock} />; } else if (muting) { buttons = <IconButton active={true} icon='volume-up' title={intl.formatMessage(messages.unmute, { name: account.get('username') })} onClick={this.handleMute} />; } else { buttons = <IconButton icon={following ? 'user-times' : 'user-plus'} title={intl.formatMessage(following ? messages.unfollow : messages.follow)} onClick={this.handleFollow} active={following} />; } } return ( <div className='account'> <div className='account__wrapper'> <Permalink key={account.get('id')} className='account__display-name' href={account.get('url')} to={`/accounts/${account.get('id')}`}> <div className='account__avatar-wrapper'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={36} /></div> <DisplayName account={account} /> </Permalink> <div className='account__relationship'> {buttons} </div> </div> </div> ); } } Account.propTypes = { account: ImmutablePropTypes.map.isRequired, me: PropTypes.number.isRequired, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, intl: PropTypes.object.isRequired } export default injectIntl(Account);
client/src/app-components/topic-edit-modal.js
ivandiazwm/opensupports
import React from 'react'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import Header from 'core-components/header'; import Button from 'core-components/button'; import Form from 'core-components/form'; import FormField from 'core-components/form-field'; import SubmitButton from 'core-components/submit-button'; import IconSelector from 'core-components/icon-selector'; import ColorSelector from 'core-components/color-selector'; import InfoTooltip from 'core-components/info-tooltip'; class TopicEditModal extends React.Component { static contextTypes = { closeModal: React.PropTypes.func }; static propTypes = { defaultValues: React.PropTypes.object, addForm: React.PropTypes.bool, topicId: React.PropTypes.number }; state = { values: this.props.defaultValues || {title: '', icon: 'address-card', color: '#ff6900', private: false}, loading: false }; render() { return ( <div className="topic-edit-modal"> <Header title={i18n((this.props.addForm) ? 'ADD_TOPIC' : 'EDIT_TOPIC')} description={i18n((this.props.addForm) ? 'ADD_TOPIC_DESCRIPTION' : 'EDIT_TOPIC_DESCRIPTION')} /> <Form values={this.state.values} onChange={this.onFormChange.bind(this)} onSubmit={this.onSubmit.bind(this)} loading={this.state.loading}> <FormField name="title" label={i18n('TITLE')} fieldProps={{size: 'large'}} validation="TITLE" required /> <FormField name="icon" className="topic-edit-modal__icon" label={i18n('ICON')} decorator={IconSelector} /> <FormField name="color" className="topic-edit-modal__color" label={i18n('COLOR')} decorator={ColorSelector} /> <FormField className="topic-edit-modal__private" label={i18n('PRIVATE')} name="private" field="checkbox"/> <InfoTooltip className="topic-edit-modal__private" text={i18n('PRIVATE_TOPIC_DESCRIPTION')} /> <SubmitButton className="topic-edit-modal__save-button" type="secondary" size="small"> {i18n('SAVE')} </SubmitButton> <Button className="topic-edit-modal__discard-button" onClick={this.onDiscardClick.bind(this)} size="small"> {i18n('CANCEL')} </Button> </Form> </div> ); } onSubmit() { this.setState({ loading: true }); API.call({ path: (this.props.addForm) ? '/article/add-topic' : '/article/edit-topic', data: { topicId: this.props.topicId, name: this.state.values['title'], icon: this.state.values['icon'], iconColor: this.state.values['color'], private: this.state.values['private']*1 } }).then(() => { this.context.closeModal(); if(this.props.onChange) { this.props.onChange(); } }).catch(() => { this.setState({ loading: false }); }); } onFormChange(form) { this.setState({ values: form }); } onDiscardClick(event) { event.preventDefault(); this.context.closeModal(); } } export default TopicEditModal;
components/feed/CabinquestFeed.js
headwinds/porthole
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getCabinquestTrees } from '../../actions/feed_cabinquest_actions'; import { getPortholeForest } from '../../actions/feed_porthole_actions'; import { getCabinQuestPark } from '../../actions/feed_cabinquest_park_actions'; import LoadingAnimation from './LoadingAnimation'; import * as _ from 'lodash'; class CabinquestFeed extends Component { constructor(props) { super(props); this.state = { branches: null }; this.getTress = this.getTrees.bind(this); } componentDidMount() { console.log('CabinquestFeed mounted'); this.getTrees(); } componentWillReceiveProps(nextProps) { console.log('CabinquestFeed componentWillReceiveProps'); if (nextProps.feed_cabinquest.branches !== null) { this.state.branches = nextProps.feed_cabinquest.branches; this.setState({ branches: nextProps.feed_cabinquest.branches }); } } getTrees() { this.props.getCabinquestTrees(); this.props.getPortholeForest(); } componentDidUpdate() { console.log( 'CabinquestFeed componentDidUpdate this.props: ', this.props ); } render() { // const { branches, portholeForest, park } = this.props.feed_cabinquest; if (portholeForest !== null) console.log( 'CabinquestFeed render portholeForest: ', portholeForest.length ); const getItems = () => { if (branches !== null && branches.length > 0) { return _.map(branches, (branch, uid) => { return ( <div className="item" key={uid}> <img src={branch.photoUrl} /> {/* <p>{branch.title}</p>*/} </div> ); }); } else return <LoadingAnimation />; }; const getPark = () => { if (park !== null && park.length > 0) { return _.map(park, (treeModel, uid) => { return ( <div className="item" key={uid}> <div>{treeModel.title}</div> </div> ); }); } else return <LoadingAnimation />; }; const getForest = () => { if (portholeForest !== null && portholeForest.length > 0) { return _.map(portholeForest, (portholeBranchModel, uid) => { return ( <div className="item" key={uid}> <img src={portholeBranchModel.photoUrl} /> <p>{portholeBranchModel.feedTitle}</p> </div> ); }); } else return <LoadingAnimation />; }; const listStyle = { height: 300, width: 300, overflow: 'hidden', overflowY: 'auto', border: '1px dashed #f1f1f1' }; const totalFeeds = this.props.feed_cabinquest.park !== null ? this.props.feed_cabinquest.park.length : 0; const getParkContainer = () => { if (this.props.auth.cabinQuestUser !== null) { return ( <div> <h2>My Trees</h2> <div style={{ ...listStyle, height: 100 }}> {getPark()} </div> <div>{totalFeeds} Feeds</div> </div> ); } else return null; }; return ( <div> {getParkContainer()} <h2>Forest</h2> <div style={listStyle}>{getForest()}</div> <h2>Trees</h2> <div style={listStyle}>{getItems()}</div> </div> ); } } const matchStateToProps = state => ({ home: state.home, auth: state.auth, feed_cabinquest: state.feed_cabinquest }); const mapDispatchToProps = dispatch => bindActionCreators( { dispatch, getCabinquestTrees, getPortholeForest, getCabinQuestPark }, dispatch ); export default connect(matchStateToProps, mapDispatchToProps)(CabinquestFeed);
app/javascript/mastodon/components/animated_number.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
src/routes/SignUpPage/components/SignUpForm/index.js
linxlad/tracksy-client
import React, { Component } from 'react'; import { Form } from 'antd'; import { Input, Button, Label, Divider, Icon } from 'semantic-ui-react'; import FacebookProvider, { Login } from 'react-facebook'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { signUpAction } from '../../actions/SignUp'; import './SignUpForm.scss'; const FormItem = Form.Item; class SignUpFormComponent extends Component { constructor(props) { super(props); this.state = { submitHover: false, artistEncouragement: null }; } handleSubmitMouseOver = () => { this.setState({ submitHover: true }); }; handleSubmitMouseOut = () => { this.setState({ submitHover: false }); }; /** * @param event */ handleSubmit = (event) => { event.preventDefault(); this.props.form.validateFields((errors, values) => { if (!errors) { this.props.signUpAction(values, (hasError) => console.log(hasError)); } }); }; handleFacebookResponse = (response) => { console.log(response); }; handleFacebookError = (error) => { console.log(error); }; handleArtistChange = () => { this.setState({ artistEncouragement: '...this is sounding awesome' }); }; /** * @return {XML}< */ render() { const { getFieldDecorator, getFieldError } = this.props.form; const { role, colour, ribbons, signup } = this.props; if (null === role) { return null; } const emailHasError = !!getFieldError('email'); const passwordHasError = !!getFieldError('password'); const artistNameHasError = !!getFieldError('artistName'); let bandNameField = null; if (role === 'artist') { bandNameField = ( <FormItem> <Label style={!ribbons ? {border: 'none', padding: 0} : {}} basic={!ribbons} color={artistNameHasError ? 'red' : colour} ribbon={ribbons}> Artist/Band name </Label> {getFieldDecorator('artistName', { rules: [ { required: true, message: 'Please enter your Artist/Band name' }, { type: 'string', message: 'Please enter a valid Artist/Band name' } ], initialValue: '' })( <div> <Input fluid type="text" size="huge" error={artistNameHasError} onChange={() => this.handleArtistChange()}/> <span>{this.state.artistEncouragement}</span> </div> )} </FormItem> ); } return ( <div className="signup-form-container"> <Divider/> <FacebookProvider appId="121403878466788"> <Login scope="email" onResponse={(response) => this.handleFacebookResponse(response)} onError={(error) => this.handleFacebookError(error)} render={({ isLoading, isWorking, onClick }) => ( <Button.Group fluid> <Button color='facebook' loading={isLoading || isWorking} onClick={onClick}> <Icon name='facebook' /> Facebook </Button> </Button.Group> )} /> </FacebookProvider> <Divider horizontal>Or</Divider> <Form onSubmit={this.handleSubmit} className="signup-form"> <FormItem> <Label style={!ribbons ? {border: 'none', padding: 0} : {}} basic={!ribbons} color={emailHasError ? 'red' : colour} ribbon={ribbons}> Email </Label> {getFieldDecorator('email', { rules: [ { required: true, message: 'Please enter a valid email' }, { type: 'email', message: 'Please enter a valid email' } ], initialValue: '' })( <Input fluid type="email" size="huge" error={emailHasError}/> )} </FormItem> <FormItem> <Label style={!ribbons ? {border: 'none', padding: 0} : {}} basic={!ribbons} color={passwordHasError ? 'red' : colour} ribbon={ribbons}> Password </Label> {getFieldDecorator('password', { rules: [ { required: true, message: 'Please enter your password' }, { type: 'string', message: 'Please enter a password' } ], initialValue: '' })( <Input fluid type="password" size="huge" error={passwordHasError}/> )} </FormItem> {bandNameField} <FormItem> <Button onMouseOver={() => this.handleSubmitMouseOver()} onMouseOut={() => this.handleSubmitMouseOut()} size='huge' loading={signup.loading} className="" color={emailHasError || passwordHasError || artistNameHasError ? 'red' : colour} basic={!this.state.submitHover} fluid> Sign Up </Button> </FormItem> </Form> </div> ); } } /** * @param state * @return {{changePasswordLoading: *, changePasswordSuccess: *, changePasswordError: *}} */ const mapStateToProps = (state) => { const { signup } = state; return { signup: signup }; }; /** * @param dispatch * @return {{signUpAction: *}|B|N} */ const mapDispatchToProps = (dispatch) => { return bindActionCreators({ signUpAction }, dispatch); }; export const SignUpForm = connect(mapStateToProps, mapDispatchToProps)(Form.create()(SignUpFormComponent));
js/components/poets/alothmani/index.js
Rebaiahmed/Alchaaer
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import { Image } from 'react-native'; import { Container, Header, Title, Content, Button, Icon, Left, Right,Card, CardItem, Text, Body, List, ListItem,Thumbnail,InputGroup, Input ,Picker,Badge,H3, Fab,Item } from 'native-base'; import {Column as Col, Row} from 'react-native-flexbox-grid'; import { openDrawer } from '../../../actions/drawer'; import styles from './styles'; var _ = require('underscore'); class PoetsAlothmaniPage extends Component { static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, } //*******************************// //*******************************// constructor(props) { super(props); //***********************************// //***********************************// //***********F//var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); } componentWillMount() { } render() { const { props: { name, index, list } } = this; return ( <Container style={styles.container}> <Header> <Body> <Title>{(name) ? this.props.name : 'العصر العثماني ' }</Title> </Body> <Right> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Right> </Header> <Content padder> <List> <ListItem> <Thumbnail square size={80} source={require('../../../../images/poetes/alabassi/aboufirass.jpeg')} /> <Body> <Text>Sankhadeep</Text> <Text note>Its time to build a difference . .</Text> </Body> </ListItem> </List> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(PoetsAlothmaniPage );
src/svg-icons/action/settings-applications.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsApplications = (props) => ( <SvgIcon {...props}> <path d="M12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm7-7H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-1.75 9c0 .23-.02.46-.05.68l1.48 1.16c.13.11.17.3.08.45l-1.4 2.42c-.09.15-.27.21-.43.15l-1.74-.7c-.36.28-.76.51-1.18.69l-.26 1.85c-.03.17-.18.3-.35.3h-2.8c-.17 0-.32-.13-.35-.29l-.26-1.85c-.43-.18-.82-.41-1.18-.69l-1.74.7c-.16.06-.34 0-.43-.15l-1.4-2.42c-.09-.15-.05-.34.08-.45l1.48-1.16c-.03-.23-.05-.46-.05-.69 0-.23.02-.46.05-.68l-1.48-1.16c-.13-.11-.17-.3-.08-.45l1.4-2.42c.09-.15.27-.21.43-.15l1.74.7c.36-.28.76-.51 1.18-.69l.26-1.85c.03-.17.18-.3.35-.3h2.8c.17 0 .32.13.35.29l.26 1.85c.43.18.82.41 1.18.69l1.74-.7c.16-.06.34 0 .43.15l1.4 2.42c.09.15.05.34-.08.45l-1.48 1.16c.03.23.05.46.05.69z"/> </SvgIcon> ); ActionSettingsApplications = pure(ActionSettingsApplications); ActionSettingsApplications.displayName = 'ActionSettingsApplications'; ActionSettingsApplications.muiName = 'SvgIcon'; export default ActionSettingsApplications;
websrc/cacti-user/src/components/ModeSelector.js
howardjones/network-weathermap
import React from 'react'; import {connect} from 'react-redux'; import {viewAllFull, viewFirstFull, viewThumbs} from '../actions'; class ModeSelector extends React.Component { constructor(props) { super(props); this.clickedFirstFull = this.clickedFirstFull.bind(this); this.clickedFull = this.clickedFull.bind(this); this.clickedThumbs = this.clickedThumbs.bind(this); } clickedThumbs() { this.props.dispatch(viewThumbs()); } clickedFull() { this.props.dispatch(viewAllFull()) } clickedFirstFull() { this.props.dispatch(viewFirstFull()) } render() { return ( <div className="ModeSelector layoutbox"> Temporary mode-selector (until settings are hooked up): <a onClick={this.clickedThumbs}>Thumbs</a> | <a onClick={this.clickedFull}>Full</a> | <a onClick={this.clickedFirstFull}>Full (first only)</a> </div> ) } } function mapStateToProps(state) { return {settings: state.settings} } export default connect(mapStateToProps)(ModeSelector);
src/containers/DevTools.js
itjope/tipskampen
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> )
src/svg-icons/av/video-library.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideoLibrary = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8 12.5v-9l6 4.5-6 4.5z"/> </SvgIcon> ); AvVideoLibrary = pure(AvVideoLibrary); AvVideoLibrary.displayName = 'AvVideoLibrary'; AvVideoLibrary.muiName = 'SvgIcon'; export default AvVideoLibrary;
src/svg-icons/hardware/devices-other.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let 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 = pure(HardwareDevicesOther); HardwareDevicesOther.displayName = 'HardwareDevicesOther'; HardwareDevicesOther.muiName = 'SvgIcon'; export default HardwareDevicesOther;
src/svg-icons/av/fiber-smart-record.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFiberSmartRecord = (props) => ( <SvgIcon {...props}> <g><circle cx="9" cy="12" r="8"/><path d="M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z"/></g> </SvgIcon> ); AvFiberSmartRecord = pure(AvFiberSmartRecord); AvFiberSmartRecord.displayName = 'AvFiberSmartRecord'; AvFiberSmartRecord.muiName = 'SvgIcon'; export default AvFiberSmartRecord;
admin/client/App/screens/Item/components/FormHeading.js
brianjd/keystone
import React from 'react'; import evalDependsOn from '../../../../../../fields/utils/evalDependsOn'; module.exports = React.createClass({ displayName: 'FormHeading', propTypes: { options: React.PropTypes.object, }, render () { if (!evalDependsOn(this.props.options.dependsOn, this.props.options.values)) { return null; } return <h3 className="form-heading">{this.props.content}</h3>; }, });
src/components/Main.js
ZhenxingXiao/zls-front-end
require('styles/App.css'); import React from 'react'; let yeomanImage = require('../images/yeoman.png'); class AppComponent extends React.Component { render() { return ( <div> <img src={yeomanImage} alt="Yeoman Generator" /> <div>Please edit <code>src/components/Main.js</code> to get started!</div> <span>first ok</span> </div> ); } } AppComponent.defaultProps = { }; export default AppComponent;
va_dashboard/tabs/integrations.js
VapourApps/va_master
import React, { Component } from 'react'; var Bootstrap = require('react-bootstrap'); var classNames = require('classnames'); import { connect } from 'react-redux'; var Network = require('../network'); import { getSpinner } from './util'; import ReactJson from 'react-json-view'; import vis from '../static/vis'; class Integrations extends Component { constructor(props) { super(props); this.state = { loading: true, showModal: false, stepIndex: 1, apps:[], functions: [], eventsPerApp: [], actionsPerApp: [], selectedDonorApp: '', selectedReceiverApp: '', selectedEvent: {}, selectedAction: {}, integrations: [] }; this.openTriggerModal=this.openTriggerModal.bind(this); this.closeModal=this.closeModal.bind(this); this.nextStep=this.nextStep.bind(this); this.addTrigger=this.addTrigger.bind(this); this.showModalButtons=this.showModalButtons.bind(this); this.getApps=this.getApps.bind(this); this.getFunctions=this.getFunctions.bind(this); this.getEventsPerApp=this.getEventsPerApp.bind(this); this.getAppPerName=this.getAppPerName.bind(this); this.reloadModal=this.reloadModal.bind(this); this.showEventsSelect=this.showEventsSelect.bind(this); this.showActionsSelect=this.showActionsSelect.bind(this); this.getFunctionPerName=this.getFunctionPerName.bind(this); this.showArgumentMapSelect=this.showArgumentMapSelect.bind(this); this.formArgumentMap=this.formArgumentMap.bind(this); this.formTriggerJSON=this.formTriggerJSON.bind(this); this.getTriggers=this.getTriggers.bind(this); this.formGraph=this.formGraph.bind(this); } componentDidMount() { var me=this; me.setState({loading: false}); this.getApps(); this.getTriggers(); //var nodes_edges_data=this.formGraph(); // create an array with nodes // var nodes = new vis.DataSet([ // {id: 1, label: 'va-email-app'}, // {id: 2, label: 'event: va_email.add_user_recipient'}, // {id: 3, label: 'event: va_email.add_user'}, // {id: 4, label: 'condition: If recipient is valid and in cloudshare'}, // {id: 5, label: 'condition: If recipient is valid'}, // {id: 6, label: 'condition: If user in ldap'}, // {id: 7, label: 'action: add_contact_to_calendar'}, // {id: 8, label: 'action: add_contact_vcard'}, // {id: 9, label: 'action: add_uesr_to_cloudshare'}, // {id: 10, label: 'va-cloudshare-app'}, // ]); //var nodes=new vis.DataSet(nodes_edges_data.nodes); // create an array with edges // var edges = new vis.DataSet([ // {from: 1, to: 2}, // {from: 1, to: 3}, // {from: 2, to: 4}, // {from: 2, to: 5}, // {from: 3, to: 6}, // {from: 4, to: 7}, // {from: 5, to: 8}, // {from: 6, to: 9}, // {from: 7, to: 10}, // {from: 8, to: 10}, // {from: 9, to: 10}, // ]); // var edges=new vis.DataSet(nodes_edges_data.edges); // // create a network // var container = document.getElementById('mynetwork'); // var data = { // nodes: nodes, // edges: edges // }; // var options = { // manipulation: false, // layout: { // hierarchical: { // direction: "LR", // sortMethod: "directed", // enabled: true, // nodeSpacing: 100, // levelSeparation: 400 // } // }, // nodes: { // shape: 'box', // borderWidth: 4, // color: '#006eab', // font:{ // color: 'white', // size: 20, // bold: true // } // } // }; // var network = new vis.Network(container, data, options); } reloadModal(){ var me=this; this.getEventsPerApp(this.state.apps[0].name); this.getActionsPerApp(this.state.apps[0].name); if(this.state.apps.length>0){ me.setState({selectedDonorApp: me.state.apps[0].name , selectedReceiverApp: me.state.apps[0].name}); me.getEventsPerApp(me.state.apps[0].name); me.getActionsPerApp(me.state.apps[0].name); } } getTriggers(){ // var integrations=[{ // "donor_app": "va-email", // "receiver_app": "va-cloudshare", // "events": [{ // "event_name": "va_email.add_user_recipient", // "conditions": [{ // "func_name": "check_user_legit" // }, { // "func_name": "check_user_in_ldap" // }], // "actions": [{ // "func_name": "add_contact_vcard" // }] // }, // { // "event_name": "va_email.add_user", // "conditions": [{ // "func_name": "check_user_legit" // }, { // "func_name": "check_user_not_in_cloudshare" // }], // "actions": [{ // "func_name": "add_cloudshare_user" // }, // { // "func_name": "add_contact_vcard" // }] // } // ] // }, // { // "donor_app": "email", // "receiver_app": "cloudshare", // "events": [{ // "event_name": "va_email.add_user_recipient", // "conditions": [{ // "func_name": "check_user_legit" // }, { // "func_name": "check_user_in_ldap" // }], // "actions": [{ // "func_name": "add_contact_vcard" // }] // }, // { // "event_name": "va_email.add_user", // "conditions": [{ // "func_name": "check_user_legit" // }, { // "func_name": "check_user_not_in_cloudshare" // }], // "actions": [{ // "func_name": "add_cloudshare_user" // }, // { // "func_name": "add_contact_vcard" // }] // } // ] // } // ]; var me=this; var integrations=[]; Network.get('api/integrations', me.props.auth.token) .done(function (data){ integrations=data; me.formGraph(integrations); }) .fail(function (msg) { me.props.dispatch({type: 'SHOW_ALERT', msg: msg}); }); } formGraph(integrations){ var ctr=0; var nodes=[]; var edges=[]; integrations.forEach(function(integration){ var receiver_app=integration.receiver_app; var donor_app=integration.donor_app; var donor_app_node={id: ctr++, label: donor_app}; var receiver_app_node={id: ctr++, label: receiver_app}; nodes.push(donor_app_node); nodes.push(receiver_app_node); var events=integration.triggers; events.forEach(function(event){ var event_node={id: ctr++, label: event.event_name}; var event_edge={from: donor_app_node.id, to: event_node.id}; nodes.push(event_node); edges.push(event_edge); var last_node={}; if(event.conditions.length == 0){ last_node=event_node; } else{ var condition_val=''; event.conditions.forEach(function(condition){ condition_val=condition_val+condition.func_name+" AND "; }); var condition_node={id: ctr++, label: condition_val}; var condition_edge={from: event_node.id, to: condition_node.id}; nodes.push(condition_node); edges.push(condition_edge); last_node=condition_node; } var actions=event.actions; actions.forEach(function(action){ var action_node={id: ctr++, label: action.func_name}; var action_edge={from: last_node.id, to: action_node.id}; var receiver_edge={from: action_node.id, to: receiver_app_node.id} nodes.push(action_node); edges.push(action_edge); edges.push(receiver_edge); }); }); }); var nodes=new vis.DataSet(nodes); var edges=new vis.DataSet(edges); // create a network var container = document.getElementById('mynetwork'); var data = { nodes: nodes, edges: edges }; var options = { manipulation: false, layout: { hierarchical: { direction: "LR", sortMethod: "directed", enabled: true, nodeSpacing: 100, levelSeparation: 400 } }, nodes: { shape: 'box', borderWidth: 4, color: '#006eab', font:{ color: 'white', size: 20, bold: true } } }; var network = new vis.Network(container, data, options); } openTriggerModal(){ this.setState({showModal: true}); } getAppPerName(appName){ return this.state.apps.filter(app => app.name == appName)[0]; } getFunctionPerName(funcName){ return this.state.functions.filter(func => func.func_name == funcName)[0]; } getApps(){ var me=this; console.log('Calling get apps'); Network.get('/api/states', this.props.auth.token) .done(function (data){ var result = data; var app_list=[]; result.forEach(function(appObject){ app_list.push(appObject); }); if(app_list.length > 0){ me.setState({selectedDonorApp: app_list[0].name, selectedReceiverApp: app_list[0].name}); } me.setState({apps: app_list}); me.getFunctions(); }) .fail(function (msg) { me.props.dispatch({type: 'SHOW_ALERT', msg: msg}); }); } getFunctions(){ var me=this; Network.get('/api/panels/get_functions', this.props.auth.token) .done(function (data){ var result = data; var functions_list=[]; result.forEach(function(functionObject){ functions_list.push(functionObject); }); me.setState({functions: functions_list}); me.getEventsPerApp(me.state.apps[0].name); me.getActionsPerApp(me.state.apps[0].name); me.setState({loading: false}); }) .fail(function (msg) { me.props.dispatch({type: 'SHOW_ALERT', msg: msg}); }); } getEventsPerApp(appName){ var app = this.getAppPerName(appName); var me=this; var event_list=[]; var result=me.state.functions; result.forEach(function(functionObject){ if(functionObject.event == true && functionObject.func_group == app.module){ event_list.push(functionObject.func_name); } }); if(event_list.length > 0){ //document.getElementById("selectEvent").disabled = false; me.setState({selectedEvent: me.getFunctionPerName(event_list[0])}); } else{ me.setState({selectedEvent: {}}); } me.setState({eventsPerApp: event_list}); } getActionsPerApp(appName){ var app = this.getAppPerName(appName); var me=this; var action_list=[]; var result=me.state.functions; result.forEach(function(functionObject){ if(functionObject.func_group == app.module){ action_list.push(functionObject.func_name); } }); if(action_list.length > 0){ //document.getElementById("selectAction").disabled = false; me.setState({selectedAction: me.getFunctionPerName(action_list[0])}); } else{ me.setState({selectedAction: {}}); } me.setState({actionsPerApp: action_list}); } closeModal(){ this.setState({showModal: false, stepIndex: 1}); this.reloadModal(); } nextStep(){ if(this.state.stepIndex < 3){ this.setState({stepIndex: this.state.stepIndex+1}); } } addTrigger(){ var me=this; console.log('ADD Trigger Button clicked'); var new_trigger=this.formTriggerJSON(); console.log('New trigger: ', new_trigger); Network.post('/api/integrations/add_trigger', this.props.auth.token, new_trigger) .done(function (data){ me.props.dispatch({type: 'SHOW_ALERT', msg: 'Succesfully added trigger'}); }) .fail(function (msg) { me.props.dispatch({type: 'SHOW_ALERT', msg: msg}); }); } handleSelectDonorAppChange(){ var select_element_value=document.getElementById('selectDonorApp').value; this.setState({selectedDonorApp: select_element_value}); this.getEventsPerApp(select_element_value); } handleSelectEventChange(){ var select_element_value=document.getElementById('selectEvent').value; var event = this.getFunctionPerName(select_element_value); this.setState({selectedEvent: event}); } handleSelectReceiverAppChange(){ var select_element_value=document.getElementById('selectReceiverApp').value; this.setState({selectedReceiverApp: select_element_value}); this.getActionsPerApp(select_element_value); } handleSelectActionChange(){ var select_element_value=document.getElementById('selectAction').value; var act = this.getFunctionPerName(select_element_value); this.setState({selectedAction: act}); } showEventsSelect(){ var event_options=this.state.eventsPerApp.map(function(event, index){ return (<option value={event}>{event}</option>); }); if(this.state.eventsPerApp.length==0){ return( <Bootstrap.FormGroup disabled> <Bootstrap.ControlLabel disabled>Select event</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectEvent" componentClass="select" placeholder="Select event" onChange={this.handleSelectEventChange.bind(this)} disabled> {event_options} </Bootstrap.FormControl> </Bootstrap.FormGroup>); } else{ return( <Bootstrap.FormGroup> <Bootstrap.ControlLabel>Select event</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectEvent" componentClass="select" placeholder="Select event" onChange={this.handleSelectEventChange.bind(this)}> {event_options} </Bootstrap.FormControl> </Bootstrap.FormGroup>); } } showActionsSelect(){ var action_options=this.state.actionsPerApp.map(function(action, index){ return (<option value={action}>{action}</option>); }); if(this.state.actionsPerApp.length==0){ return( <Bootstrap.FormGroup disabled> <Bootstrap.ControlLabel disabled>Select action</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectAction" componentClass="select" placeholder="Select action" onChange={this.handleSelectActionChange.bind(this)} disabled> {action_options} </Bootstrap.FormControl> </Bootstrap.FormGroup>); } else{ return( <Bootstrap.FormGroup> <Bootstrap.ControlLabel>Select action</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectAction" componentClass="select" placeholder="Select action" onChange={this.handleSelectActionChange.bind(this)}> {action_options} </Bootstrap.FormControl> </Bootstrap.FormGroup>); } } showModalButtons(){ if(this.state.stepIndex == 3){ return ( <Bootstrap.ButtonGroup> <Bootstrap.Button bsStyle='primary' onClick={this.addTrigger} style={{marginRight: '5px'}}> Submit </Bootstrap.Button> <Bootstrap.Button onClick={()=> this.closeModal()}> Close </Bootstrap.Button> </Bootstrap.ButtonGroup> ); } else { return ( <Bootstrap.ButtonGroup> <Bootstrap.Button bsStyle='primary' onClick={this.nextStep} style={{marginRight: '5px'}}> <Bootstrap.Glyphicon glyph='menu-right'></Bootstrap.Glyphicon> Next step</Bootstrap.Button> <Bootstrap.Button onClick={()=> this.closeModal()}> Close </Bootstrap.Button> </Bootstrap.ButtonGroup> ); } } showArgumentMapSelect(){ var me=this; if(me.state.selectedAction.hasOwnProperty('arguments') && me.state.selectedEvent.hasOwnProperty('arguments')){ var action_args=me.state.selectedAction.arguments; var event_args=me.state.selectedEvent.arguments; var elements=[]; action_args.forEach(function(action_arg){ var element_options=[]; event_args.forEach(function(event_arg, index){ element_options.push( <option value={event_arg.name}>{event_arg.name}</option> ); }); element_options.push( <option value="No mapping">No mapping</option>); elements.push( <Bootstrap.FormGroup> <Bootstrap.ControlLabel>{action_arg.name}</Bootstrap.ControlLabel> <Bootstrap.FormControl id={action_arg.name} componentClass="select"> {element_options} </Bootstrap.FormControl> </Bootstrap.FormGroup> ); }); return elements; } } formArgumentMap(){ var me=this; var args_map={}; if(me.state.selectedAction.hasOwnProperty('arguments') && me.state.selectedEvent.hasOwnProperty('arguments')){ console.log('IN'); var action_args=me.state.selectedAction.arguments; var event_args=me.state.selectedEvent.arguments; action_args.forEach(function(action_arg){ var select_element_value=document.getElementById(action_arg.name).value; if(select_element_value == 'No mapping'){ } else{ args_map[action_arg.name]=select_element_value; } }); } console.log('Args Map: ', args_map); return args_map; } formTriggerJSON(){ var me=this; var data={}; var args_map=this.formArgumentMap(); data['donor_app']=me.state.selectedDonorApp; data['receiver_app']=me.state.selectedReceiverApp; var trigger={}; trigger['event_name']=me.state.selectedEvent.func_group+"."+me.state.selectedEvent.func_name; trigger['conditions']=[]; trigger['actions']=[{"args_map": args_map, "func_name": me.state.selectedAction.func_name}] data['trigger']=trigger; console.log(data); return data; } render() { var me=this; var loading = this.state.loading; var app_options=this.state.apps.map(function(app, index){ return (<option value={app.name}>{app.name}</option>); }); return ( <div> {loading && getSpinner()} <div style={this.props.style} className="card"> <div className="card-body"> <table className="table striped"> <thead> <tr className="reactable-filterer"> <td> <h4>Integrations</h4> </td> <td style={{textAlign: 'right'}}> <Bootstrap.Button onClick={()=> this.openTriggerModal()}> <Bootstrap.Glyphicon glyph='plus' /> Create trigger </Bootstrap.Button> </td> </tr> </thead> </table> <div id="mynetwork"></div> <Bootstrap.Modal show={this.state.showModal} onHide={this.closeModal}> <Bootstrap.Modal.Header> <Bootstrap.Modal.Title> Add Trigger</Bootstrap.Modal.Title> </Bootstrap.Modal.Header> <Bootstrap.Modal.Body> <Bootstrap.Tabs id="tabs" activeKey={this.state.stepIndex}> <Bootstrap.Tab eventKey={1} title="Step 1"> <Bootstrap.FormGroup> <Bootstrap.ControlLabel>Select Donor app</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectDonorApp" componentClass="select" placeholder="Select donor app" onChange={this.handleSelectDonorAppChange.bind(this)}> {app_options} </Bootstrap.FormControl> </Bootstrap.FormGroup> {this.showEventsSelect()} </Bootstrap.Tab> <Bootstrap.Tab eventKey={2} title="Step 2"> <Bootstrap.FormGroup> <Bootstrap.ControlLabel>Select Receiver app</Bootstrap.ControlLabel> <Bootstrap.FormControl id="selectReceiverApp" componentClass="select" placeholder="Select Receiver app" onChange={this.handleSelectReceiverAppChange.bind(this)}> {app_options} </Bootstrap.FormControl> </Bootstrap.FormGroup> {this.showActionsSelect()} </Bootstrap.Tab> <Bootstrap.Tab eventKey={3} title="Step 3"> <h5>Arguments map</h5> <hr/> <div>{/*<h4>Donor app: {this.state.selectedDonorApp}</h4> <h4>Receiver app: {this.state.selectedReceiverApp}</h4> <h4>Event: {JSON.stringify(this.state.selectedEvent)}</h4> <h4>Action: {JSON.stringify(this.state.selectedAction)}</h4>*/}</div> {this.showArgumentMapSelect()} </Bootstrap.Tab> </Bootstrap.Tabs> </Bootstrap.Modal.Body> <Bootstrap.Modal.Footer> {this.showModalButtons()} </Bootstrap.Modal.Footer> </Bootstrap.Modal> <br/> </div> </div> </div>); } } module.exports = connect(state => { return { auth: state.auth, alert: state.alert }; })(Integrations);
components/GameArticles.js
turntwogg/final-round
import React from 'react'; import Typography from './Typography'; import Scroller from './Scroller'; import DashboardArticle from './DashboardArticle'; import GameSection, { GameSectionHeader } from './GameSection'; import Button from './Button'; import Skeleton, { Item } from './SkeletonNew'; const GameArticles = ({ count, game, articles, ...rest }) => { return ( <GameSection> <GameSectionHeader> <Typography is="h2" variant="no-spacing"> Recent News </Typography> <Button href="/games/[slug]/news" as={`/games/${game.fieldGameSlug}/news`} > View All News </Button> </GameSectionHeader> <Scroller> {articles.fetching ? ( <Skeleton count={count} dir="horizontal" left={<Item type="image" size="small" width={32} />} right={ <> <Item /> <Item /> </> } /> ) : ( articles.data.map(article => ( <DashboardArticle article={article} key={article.id} hasBorder={false} style={{ marginBottom: 0 }} /> )) )} </Scroller> </GameSection> ); }; export default GameArticles;
15-react-router-v4/src/components/repos.js
iproduct/course-node-express-react
import React from 'react'; import { PropTypes } from 'prop-types'; import Repo from './repo'; import { Route } from 'react-router-dom'; const Repos = (props) => { return ( <div> <h2>Repos</h2> <Route path="/repos/:userName/:repoName" component={Repo} /> </div> ); }; Repos.propTypes = { children: PropTypes.node } export default Repos;
dashboard/src/components/dashboard/history/HistoryList.js
leapfrogtechnology/chill
import React from 'react'; import PropTypes from 'prop-types'; import Incident from './Incident'; import IncidentRow from './IncidentRow'; /** * List of past incidents. * * @param {Array} incidents */ const HistoryList = ({ incidents }) => { return ( <> {incidents.map(group => ( <div className="incidents-block" key={group.date}> <IncidentRow data={group.date} /> {group.list.map(incident => ( <Incident data={incident} key={incident.id} /> ))} </div> ))} </> ); }; HistoryList.propTypes = { incidents: PropTypes.array }; export default HistoryList;
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js
Ajunboys/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import ReactZeroClipboard from 'react-zeroclipboard'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, Snackbar } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import classnames from 'classnames'; //import { Experiment, Variant } from 'react-ab'; //import mixpanel from 'utils/Mixpanel'; import DialogActionCreators from 'actions/DialogActionCreators'; import GroupProfileActionCreators from 'actions/GroupProfileActionCreators'; import LoginStore from 'stores/LoginStore'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import GroupStore from 'stores/GroupStore'; import InviteUserActions from 'actions/InviteUserActions'; import AvatarItem from 'components/common/AvatarItem.react'; import InviteUser from 'components/modals/InviteUser.react'; import InviteByLink from 'components/modals/invite-user/InviteByLink.react'; import GroupProfileMembers from 'components/activity/GroupProfileMembers.react'; import Fold from 'components/common/Fold.React'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = (groupId) => { const thisPeer = PeerStore.getGroupPeer(groupId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer), integrationToken: GroupStore.getIntegrationToken() }; }; @ReactMixin.decorate(IntlMixin) class GroupProfile extends React.Component { static propTypes = { group: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = _.assign({ isMoreDropdownOpen: false }, getStateFromStores(props.group.id)); ThemeManager.setTheme(ActorTheme); DialogStore.addNotificationsListener(this.onChange); GroupStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeNotificationsListener(this.onChange); GroupStore.removeChangeListener(this.onChange); } componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.group.id)); } onAddMemberClick = group => { InviteUserActions.show(group); }; onLeaveGroupClick = groupId => { DialogActionCreators.leaveGroup(groupId); }; onNotificationChange = event => { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); }; onChange = () => { this.setState(getStateFromStores(this.props.group.id)); }; selectToken = (event) => { event.target.select(); }; onIntegrationTokenCopied = () => { this.refs.integrationTokenCopied.show(); }; toggleMoreDropdown = () => { const isMoreDropdownOpen = this.state.isMoreDropdownOpen; if (!isMoreDropdownOpen) { this.setState({isMoreDropdownOpen: true}); document.addEventListener('click', this.closeMoreDropdown, false); } else { this.closeMoreDropdown(); } }; closeMoreDropdown = () => { this.setState({isMoreDropdownOpen: false}); document.removeEventListener('click', this.closeMoreDropdown, false); }; render() { const group = this.props.group; const myId = LoginStore.getMyId(); const isNotificationsEnabled = this.state.isNotificationsEnabled; const integrationToken = this.state.integrationToken; const admin = GroupProfileActionCreators.getUser(group.adminId); const isMember = DialogStore.isGroupMember(group); const snackbarStyles = ActorTheme.getSnackbarStyles(); let adminControls; if (group.adminId === myId) { adminControls = [ <li className="dropdown__menu__item hide"> <i className="material-icons">photo_camera</i> <FormattedMessage message={this.getIntlMessage('setGroupPhoto')}/> </li> , <li className="dropdown__menu__item hide"> <svg className="icon icon--dropdown" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/> <FormattedMessage message={this.getIntlMessage('addIntegration')}/> </li> , <li className="dropdown__menu__item hide"> <i className="material-icons">mode_edit</i> <FormattedMessage message={this.getIntlMessage('editGroup')}/> </li> , <li className="dropdown__menu__item hide"> <FormattedMessage message={this.getIntlMessage('deleteGroup')}/> </li> ]; } let members = <FormattedMessage message={this.getIntlMessage('members')} numMembers={group.members.length}/>; let dropdownClassNames = classnames('dropdown pull-right', { 'dropdown--opened': this.state.isMoreDropdownOpen }); const iconElement = ( <svg className="icon icon--green" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#members"/>'}}/> ); const groupMeta = [ <header> <AvatarItem image={group.bigAvatar} placeholder={group.placeholder} size="big" title={group.name}/> <h3 className="group_profile__meta__title">{group.name}</h3> <div className="group_profile__meta__created"> <FormattedMessage admin={admin.name} message={this.getIntlMessage('createdBy')}/> </div> </header> , <div className="group_profile__meta__description hide"> Description here </div> ]; if (isMember) { return ( <div className="activity__body group_profile"> <ul className="profile__list"> <li className="profile__list__item group_profile__meta"> {groupMeta} <footer> <button className="button button--light-blue pull-left" onClick={this.onAddMemberClick.bind(this, group)}> <i className="material-icons">person_add</i> <FormattedMessage message={this.getIntlMessage('addPeople')}/> </button> <div className={dropdownClassNames}> <button className="dropdown__button button button--light-blue" onClick={this.toggleMoreDropdown}> <i className="material-icons">more_horiz</i> <FormattedMessage message={this.getIntlMessage('more')}/> </button> <ul className="dropdown__menu dropdown__menu--right"> {adminControls} <li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.onLeaveGroupClick.bind(this, group.id)}> <FormattedMessage message={this.getIntlMessage('leaveGroup')}/> </li> </ul> </div> </footer> </li> <li className="profile__list__item group_profile__media no-p hide"> <Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}> <ul> <li><a>230 Shared Photos and Videos</a></li> <li><a>49 Shared Links</a></li> <li><a>49 Shared Files</a></li> </ul> </Fold> </li> <li className="profile__list__item group_profile__notifications no-p"> <label htmlFor="notifications"> <i className="material-icons icon icon--squash">notifications_none</i> <FormattedMessage message={this.getIntlMessage('notifications')}/> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </label> </li> <li className="profile__list__item group_profile__members no-p"> <Fold iconElement={iconElement} title={members}> <GroupProfileMembers groupId={group.id} members={group.members}/> </Fold> </li> <li className="profile__list__item group_profile__integration no-p"> <Fold icon="power" iconClassName="icon--pink" title="Integration Token"> <div className="info info--light"> If you have programming chops, or know someone who does, this integration token allow the most flexibility and communication with your own systems. <a href="https://actor.readme.io/docs/simple-integration" target="_blank">Learn how to integrate</a> <ReactZeroClipboard onCopy={this.onIntegrationTokenCopied} text={integrationToken}> <a>Copy integration link</a> </ReactZeroClipboard> </div> <textarea className="token" onClick={this.selectToken} readOnly row="3" value={integrationToken}/> </Fold> </li> </ul> <InviteUser/> <InviteByLink/> <Snackbar autoHideDuration={3000} message={this.getIntlMessage('integrationTokenCopied')} ref="integrationTokenCopied" style={snackbarStyles}/> </div> ); } else { return ( <div className="activity__body group_profile"> <ul className="profile__list"> <li className="profile__list__item group_profile__meta"> {groupMeta} </li> </ul> </div> ); } } } export default GroupProfile;
src/scenes/Dashboard/AddTask/AddTask.js
jmlweb/paskman
import React from 'react'; import PT from 'prop-types'; import Modal from '../../../components/Modal/ModalContainer'; import { FieldSet, Form, FormGroup, Label, OptionsSwitcher, RangeSlider, TextField, } from '../../../components/Form'; import ButtonBar from '../../../components/ButtonBar/ButtonBar'; import Button from '../../../components/Button/Button'; import constants from '../constants'; function dummy() { return false; } export const AddTask = ({ name, description, handleNameChange, handleNameBlur, handleDescriptionChange, }) => ( <Form noSpacing noValidate> <FieldSet> <FormGroup> <Label>Name (3 chars min)</Label> <TextField id="name" type="text" minLength="3" placeholder="Try to be concise" value={name.value} onChange={handleNameChange} onBlur={handleNameBlur} error={!name.isValid && name.hasChanged && 'Please, enter 3 characters at least'} required /> </FormGroup> <FormGroup> <Label>Description</Label> <TextField textarea id="description" placeholder="Describe the task" cols="80" rows="4" value={description} onChange={handleDescriptionChange} /> </FormGroup> {( <FormGroup> <Label>Pomodoros required</Label> <OptionsSwitcher options={[1, 2, 3, 4, 5].map(pomodoros => ({ description: `${pomodoros}`, value: pomodoros * 25, // @todo Load time from settings }))} value={1 * 25} onChange={dummy} /> <ButtonBar right> <Button type="button" color="primary" size="sm">Change to time</Button> </ButtonBar> </FormGroup> )} { 1 === 3 && ( <FormGroup> <Label>Time required</Label> <RangeSlider tooltip={false} min={5} max={75} step={5} onChange={dummy} /> <ButtonBar right> <Button type="button" color="primary" size="sm">Change to pomodoros</Button> </ButtonBar> </FormGroup> )} </FieldSet> <Button type="submit" color="success" block>Save</Button> </Form> ); AddTask.propTypes = { name: PT.shape({ hasChanged: PT.bool, value: PT.string, isValid: PT.bool, }).isRequired, description: PT.string.isRequired, handleNameChange: PT.func.isRequired, handleNameBlur: PT.func.isRequired, handleDescriptionChange: PT.func.isRequired, }; const AddTaskWithModal = props => ( <Modal name={constants.addTaskModalName} title="Add new task"> <AddTask {...props} /> </Modal> ); export default AddTaskWithModal;
Sources/ewsnodejs-server/node_modules/@material-ui/core/RootRef/RootRef.js
nihospr01/OpenSpeechPlatform-UCSD
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var React = _interopRequireWildcard(require("react")); var ReactDOM = _interopRequireWildcard(require("react-dom")); var _propTypes = _interopRequireDefault(require("prop-types")); var _utils = require("@material-ui/utils"); var _setRef = _interopRequireDefault(require("../utils/setRef")); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * ⚠️⚠️⚠️ * If you want the DOM element of a Material-UI component check out * [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element) * first. * * This component uses `findDOMNode` which is deprecated in React.StrictMode. * * Helper component to allow attaching a ref to a * wrapped element to access the underlying DOM element. * * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801. * For example: * ```jsx * import React from 'react'; * import RootRef from '@material-ui/core/RootRef'; * * function MyComponent() { * const domRef = React.useRef(); * * React.useEffect(() => { * console.log(domRef.current); // DOM node * }, []); * * return ( * <RootRef rootRef={domRef}> * <SomeChildComponent /> * </RootRef> * ); * } * ``` */ var RootRef = /*#__PURE__*/function (_React$Component) { (0, _inherits2.default)(RootRef, _React$Component); var _super = _createSuper(RootRef); function RootRef() { (0, _classCallCheck2.default)(this, RootRef); return _super.apply(this, arguments); } (0, _createClass2.default)(RootRef, [{ key: "componentDidMount", value: function componentDidMount() { this.ref = ReactDOM.findDOMNode(this); (0, _setRef.default)(this.props.rootRef, this.ref); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var ref = ReactDOM.findDOMNode(this); if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) { if (prevProps.rootRef !== this.props.rootRef) { (0, _setRef.default)(prevProps.rootRef, null); } this.ref = ref; (0, _setRef.default)(this.props.rootRef, this.ref); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.ref = null; (0, _setRef.default)(this.props.rootRef, null); } }, { key: "render", value: function render() { return this.props.children; } }]); return RootRef; }(React.Component); process.env.NODE_ENV !== "production" ? RootRef.propTypes = { /** * The wrapped element. */ children: _propTypes.default.element.isRequired, /** * A ref that points to the first DOM node of the wrapped element. */ rootRef: _utils.refType.isRequired } : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== "production" ? RootRef.propTypes = (0, _utils.exactProp)(RootRef.propTypes) : void 0; } var _default = RootRef; exports.default = _default;
app/pages/catalogpage/CatalogPage.js
Laastine/lukkarimaatti
import React from 'react' import PropTypes from 'prop-types' import Catalog from './Catalog' import Header from '../../partials/header' import Footer from '../../partials/footer' import {loadCourses, loadCoursesByDepartment} from '../frontApi/lukkariApi' class CatalogPage extends React.Component { render() { return <div> <div className='content-container'> <Header state={this.context.appState}/> <Catalog state={this.context.appState}/> <Footer/> </div> </div> } } CatalogPage.displayName = 'CatalogPage' CatalogPage.needs = [loadCoursesByDepartment, loadCourses] CatalogPage.contextTypes = { appState: PropTypes.object } CatalogPage.propTypes = { appState: PropTypes.object } export default CatalogPage
src/app/core/atoms/icon/icons/list.js
blowsys/reservo
import React from 'react'; const List = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><g transform="translate(5.000000, 7.000000)"><polygon points="0 2 2 2 2 0 0 0"/><polygon points="4 2 14 2 14 0 4 0"/><polygon points="0 6 2 6 2 4 0 4"/><polygon points="4 6 14 6 14 4 4 4"/><polygon points="0 10 2 10 2 8 0 8"/><polygon points="4 10 14 10 14 8 4 8"/></g></g></g></svg>; export default List;
app/src/containers/ResumePDF/ResumePDF.js
RyanCCollins/ryancollins.io
import React from 'react'; import { PDFViewer } from '../../components'; const ResumePDF = () => ( <PDFViewer url="https://s3.amazonaws.com/accredible-profile-uploads/udacity/resumes/1469994565898" /> ); export default ResumePDF;
packages/wix-style-react/src/Carousel/SliderArrow/SliderArrow.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from '../../IconButton/IconButton'; import { classes } from '../Carousel.st.css'; const skinPriorityMap = { standard: 'secondary', inverted: 'primary', light: 'primary', transparent: 'primary', premium: 'primary', }; const SliderArrow = ({ dataHook, arrowSize, buttonSkin, icon, className, controlsStartEnd, ...remainingProps }) => { const isControlOnEdge = className.includes('slick-disabled'); return isControlOnEdge && controlsStartEnd === 'hidden' ? null : ( <div {...remainingProps} data-hook={dataHook} className={className}> <IconButton className={classes.controls} skin={buttonSkin} size={arrowSize} disabled={isControlOnEdge} priority={skinPriorityMap[buttonSkin]} > {icon} </IconButton> </div> ); }; SliderArrow.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** Icon to be rendered within the icon button */ icon: PropTypes.element.isRequired, }; export default SliderArrow;
src/js/prop_types.js
rafaelfbs/realizejs
import React from 'react'; import i18n from './i18n/i18n'; export default { ...React.PropTypes, localizedString(props, propName, componentName) { const value = props[propName]; if (value === null || value === undefined || (typeof value === 'string' && value.length === 0)) { return null; } const translatedValue = i18n.t(value); if (typeof value !== 'string' || typeof translatedValue !== 'string' || translatedValue.length === 0) { return new Error(`Property ${propName} from ${componentName} is not a localized string`); } return null; }, component: React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.element, React.PropTypes.string, ]), };
packages/app/app/components/LibraryView/LibraryFolders/index.js
nukeop/nuclear
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { Button, Divider, Icon, List, Segment, Progress } from 'semantic-ui-react'; import { withTranslation } from 'react-i18next'; import { compose, withHandlers } from 'recompose'; import styles from './styles.scss'; const LibraryFolders = ({ openLocalFolderPicker, scanLocalFolders, onRemoveClick, localFolders, scanTotal, scanProgress, loading, t }) => ( <Segment className={styles.library_folders}> <Segment className={styles.control_bar}> <Button icon inverted labelPosition='left' className={styles.add_folder} onClick={openLocalFolderPicker} > <Icon name='folder open' /> {t('add')} </Button> <Button inverted icon='refresh' disabled={_.isEmpty(localFolders)} loading={loading} onClick={scanLocalFolders} className={styles.refresh_icon} /> </Segment> { scanTotal && <Progress className={styles.progress_bar} value={scanProgress} total={scanTotal} progress='ratio' /> } { !_.isEmpty(localFolders) && <> <Divider /> <List divided verticalAlign='middle' className={styles.equalizer_list}> {localFolders.map((folder, idx) => ( <List.Item key={idx}> <List.Content floated='right'> <Icon name='close' onClick={() => onRemoveClick(folder)} className={styles.folder_remove_icon} /> </List.Content> <List.Content>{folder}</List.Content> </List.Item> ))} </List> </> } </Segment> ); LibraryFolders.propTypes = { openLocalFolderPicker: PropTypes.func, scanLocalFolders: PropTypes.func, removeLocalFolder: PropTypes.func, localFolders: PropTypes.array, loading: PropTypes.bool }; export default compose( withTranslation('library'), withHandlers({ onRemoveClick: ({removeLocalFolder}) => folder => removeLocalFolder(folder) }) )(LibraryFolders);
src/svg-icons/image/healing.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageHealing = (props) => ( <SvgIcon {...props}> <path d="M17.73 12.02l3.98-3.98c.39-.39.39-1.02 0-1.41l-4.34-4.34c-.39-.39-1.02-.39-1.41 0l-3.98 3.98L8 2.29C7.8 2.1 7.55 2 7.29 2c-.25 0-.51.1-.7.29L2.25 6.63c-.39.39-.39 1.02 0 1.41l3.98 3.98L2.25 16c-.39.39-.39 1.02 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34c.39-.39.39-1.02 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z"/> </SvgIcon> ); ImageHealing = pure(ImageHealing); ImageHealing.displayName = 'ImageHealing'; ImageHealing.muiName = 'SvgIcon'; export default ImageHealing;
javascript/ql/test/query-tests/Expressions/UnboundEventHandlerReceiver/tst.js
github/codeql
import React from 'react'; import autoBind from 'auto-bind'; import reactAutobind from 'react-autobind'; class Component0 extends React.Component { render() { return <div> <div onClick={this.bound_throughAutoBind}/> // OK </div> } constructor(props) { super(props); autoBind(this); } bound_throughAutoBind() { this.setState({ }); } } class Component1 extends React.Component { render() { var unbound3 = this.unbound3; return <div> <div onClick={this.unbound1}/> // NOT OK <div onClick={this.unbound2}/> // NOT OK <div onClick={unbound3}/> // NOT OK <div onClick={this.bound_throughBindInConstructor}/> // OK <div onClick={this.bound_throughDeclaration}/> // OK <div onClick={this.unbound_butNoThis}/> // OK <div onClick={this.unbound_butNoThis2}/> // OK <div onClick={(e) => this.unbound_butInvokedSafely(e)}/> // OK <div onClick={this.bound_throughBindInMethod}/> // OK <div onClick={this.bound_throughNonSyntacticBindInConstructor}/> // OK <div onClick={this.bound_throughBindAllInConstructor1}/> // OK <div onClick={this.bound_throughBindAllInConstructor2}/> // OK <div onClick={this.bound_throughDecorator_autobind}/> // OK <div onClick={this.bound_throughDecorator_actionBound}/> // OK </div> } constructor(props) { super(props); this.bound_throughBindInConstructor = this.bound_throughBindInConstructor.bind(this); this.bound_throughBizarreBind = foo.bar.bind(baz); var cmp = this; var bound = (cmp.bound_throughNonSyntacticBindInConstructor.bind(this)); (cmp).bound_throughNonSyntacticBindInConstructor = bound; _.bindAll(this, 'bound_throughBindAllInConstructor1'); _.bindAll(this, ['bound_throughBindAllInConstructor2']); } unbound1() { this.setState({ }); } unbound2() { () => this.setState({ }); } unbound3() { () => this.setState({ }); } bound_throughBindInConstructor() { this.setState({ }); } bound_throughNonSyntacticBindInConstructor() { this.setState({ }); } bound_throughBizzareBind() { this.setState({ }); } bound_throughDeclaration = () => { this.setState({ }); } unbound_butNoThis1() { } unbound_butNoThis2() { (function(){ this.setState({ })}); } unbound_butInvokedSafely() { this.setState({ }); } componentWillMount() { this.bound_throughBindInMethod = this.bound_throughBindInMethod.bind(this); } bound_throughBindInMethod() { this.setState({ }); } bound_throughBindAllInConstructor1() { this.setState({ }); } bound_throughBindAllInConstructor2() { this.setState({ }); } @autobind bound_throughDecorator_autobind() { this.setState({ }); } @action.bound bound_throughDecorator_actionBound() { this.setState({ }); } } @autobind class Component2 extends React.Component { render() { return <div> <div onClick={this.bound_throughClassDecorator_autobind}/> // OK </div>; } bound_throughClassDecorator_autobind() { this.setState({ }); } } class Component3 extends React.Component { render() { return <div> <div onClick={this.bound_throughIterator}/> // OK </div> } constructor(props) { super(props); Object.getOwnPropertyNames( Component3.prototype ) .filter( prop => typeof this[ prop ] === 'function' ) .forEach( prop => ( this[ prop ] = this[ prop ].bind( this ) ) ); } bound_throughIterator() { this.setState({ }); } } class Component4 extends React.Component { render() { return <div> <div onClick={this.bound_throughReactAutobind}/> // OK </div> } constructor(props) { super(props); reactAutobind(this); } bound_throughReactAutobind() { this.setState({ }); } } class Component5 extends React.Component { render() { return <div> <div onClick={this.bound_throughSomeBinder}/> // OK </div> } constructor(props) { super(props); someBind(this, "bound_throughSomeBinder"); } bound_throughSomeBinder() { this.setState({ }); } }
Paths/React/05.Building Scalable React Apps/2-react-boilerplate-building-scalable-apps-m2-exercise-files/After/app/containers/NotFoundPage/index.js
phiratio/Pluralsight-materials
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
react/react-demo/src/App.js
Arguiwu/code-snippet
import React, { Component } from 'react'; import { ApolloClient, gql, graphql, ApolloProvider, } from 'react-apollo' import logo from './logo.svg'; import './App.css'; const client = new ApolloClient() const channelsListQuery = gql` query ChannelsListQuery { channels { id name } } ` const ChannelsList = ({ data: {loading, error, channels}}) => { if(loading) { return <p>Loading ...</p> } if(error) { return <p>{error.message}</p> } return <ul className="Item-list"> { channels.map( ch => <li key={ch.id}>{ch.name}</li>)} </ul> } const ChannelsListWithData = graphql(channelsListQuery)(ChannelsList); class App extends Component { render() { return ( <ApolloProvider client={client}> <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to Apollo</h2> </header> <ChannelsListWithData /> </div> </ApolloProvider> ); } } export default App;
lesson-5/src/components/editNotesPage/EditNoteModal.js
msd-code-academy/lessons
import React from 'react' import Modal from 'react-modal' import '../../styles/EditNoteModal.css' class EditNoteModal extends React.Component { constructor(props) { super(props) this.state = { modalIsOpen: false, note: { uuid: props.noteUuid, text: props.text, title: props.title, }, } } toggleModal = () => { this.setState({ modalIsOpen: !this.state.modalIsOpen, }) } handleChange = field => e => { let note = this.state.note note[field] = e.target.value this.setState({ note }) } handleFormSubmit = e => { e.preventDefault() this.props.editNote(this.state.note) this.toggleModal() } render() { const { modalIsOpen } = this.state return ( <div className="EditNoteModal"> <a onClick={this.toggleModal}>edit</a> <Modal isOpen={modalIsOpen} onRequestClose={this.toggleModal} className="EditNoteModal-modal-window" overlayClassName="EditNoteModal-modal-overlay" > <h2>Edit a note</h2> <form onSubmit={this.handleFormSubmit}> <div> <label htmlFor="title">Title</label> <input type="text" id="title" value={this.state.note.title} onChange={this.handleChange('title')} /> </div> <div className="EditNoteModal-textarea"> <label htmlFor="text">Text</label> <textarea rows="4" id="text" value={this.state.note.text} onChange={this.handleChange('text')} /> </div> <button type="submit">Submit</button> </form> </Modal> </div> ) } } export default EditNoteModal
loc8-react-redux-front-end/src/components/Article/CommentInput.js
uberslackin/django-redux-loc8-ARweb
import React from 'react'; import agent from '../../agent'; import { connect } from 'react-redux'; const mapDispatchToProps = dispatch => ({ onSubmit: payload => dispatch({ type: 'ADD_COMMENT', payload }) }); class CommentInput extends React.Component { constructor() { super(); this.state = { body: '' }; this.setBody = ev => { this.setState({ body: ev.target.value }); }; this.createComment = ev => { ev.preventDefault(); const payload = agent.Comments.create(this.props.slug, { body: this.state.body }); this.setState({ body: '' }); this.props.onSubmit(payload); }; } render() { return ( <form className="card comment-form" onSubmit={this.createComment}> <div className="card-block"> <textarea className="form-control" placeholder="Write a comment..." value={this.state.body} onChange={this.setBody} rows="3"> </textarea> </div> <div className="card-footer"> <img src={this.props.currentUser.image} className="comment-author-img" /> <button className="btn btn-sm btn-primary" type="submit"> Post Comment </button> </div> </form> ); } } export default connect(() => ({}), mapDispatchToProps)(CommentInput);
docs/app/Examples/elements/Input/Variations/InputExampleActionIconButton.js
vageeshb/Semantic-UI-React
import React from 'react' import { Input } from 'semantic-ui-react' const InputExampleActionIconButton = () => ( <Input action={{ icon: 'search' }} placeholder='Search...' /> ) export default InputExampleActionIconButton
js/app.js
matthewbdaly/react-app-skeleton
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link } from 'react-router'; import Page from './components/page'; import NoMatch from './components/nomatch'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import styles from '../scss/style.scss'; const history = createBrowserHistory(); ReactDOM.render( <Router history={history}> <Route path="/" component={Page} /> <Route path="*" component={NoMatch}/> </Router>, document.getElementById('view') );
app/components/ReposList/index.js
vinhtran19950804/procure_react
import React from 'react'; import PropTypes from 'prop-types'; import List from 'components/List'; import ListItem from 'components/ListItem'; import LoadingIndicator from 'components/LoadingIndicator'; import RepoListItem from 'containers/RepoListItem'; function ReposList({ loading, error, repos }) { if (loading) { return <List component={LoadingIndicator} />; } if (error !== false) { const ErrorComponent = () => ( <ListItem item={'Something went wrong, please try again!'} /> ); return <List component={ErrorComponent} />; } if (repos !== false) { return <List items={repos} component={RepoListItem} />; } return null; } ReposList.propTypes = { loading: PropTypes.bool, error: PropTypes.any, repos: PropTypes.any, }; export default ReposList;
docs/app/Examples/elements/Label/Variations/LabelExampleCircular.js
mohammed88/Semantic-UI-React
import React from 'react' import { Label } from 'semantic-ui-react' const colors = [ 'red', 'orange', 'yellow', 'olive', 'green', 'teal', 'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black', ] const LabelExampleCircular = () => ( <div> {colors.map(color => <Label circular color={color} key={color}>2</Label>)} </div> ) export default LabelExampleCircular
Examples/Example.ChromiumFx.Mobx.UI/View/mainview/src/App.js
David-Desmaisons/MVVM.CEF.Glue
import React, { Component } from 'react'; import { observer } from 'mobx-react'; import CommandButton from './component/CommandButton'; import Skill from './component/Skill'; import logo from './logo.svg'; import './App.css'; @observer export default class App extends Component { constructor(props) { super(props); this.handleInputChange = this.handleInputChange.bind(this); this.handleCityChange = this.handleCityChange.bind(this); } handleInputChange(event) { const target = event.target; const value = target.type === 'range' ? Number(target.value) : target.value; const name = target.name; this.props.viewModel[name] = value; } handleCityChange(event) { const value = event.target.value; this.props.viewModel.Local.City = value; } handleOptionChange(option, event){ this.props.viewModel.PersonalState = option; } render() { const vm = this.props.viewModel; return ( <div id="app" className="fluid container"> <div className="jumbotron logo"> <img src={logo} className="App-logo" alt="logo" /> <h4>Welcome to Neutronium-Mobx-React</h4> </div> <form> <div className="form-group"> <label htmlFor="name">Name</label> <input id="name" name="Name" placeholder="Name" className="form-control" value={vm.Name} onChange={this.handleInputChange} /> </div> <div className="form-group"> <label htmlFor="Last">Last Name</label> <input id="Last" name="LastName" placeholder="Last Name" className="form-control" value={vm.LastName} onChange={this.handleInputChange} /> </div> <div className="form-group"> <label htmlFor="City">City</label> <input id="City" placeholder="City" className="form-control" value={vm.Local.City} onChange={this.handleCityChange} /> </div> <div className="form-group"> <label htmlFor="Age">Age {vm.Age} years</label> <input type="range" id="Age" name="Age" className="form-control" value={vm.Age} onChange={this.handleInputChange} /> </div> <div className="form-group" > <label htmlFor="state">State: {vm.PersonalState.displayName}</label> <div id="state" className="checkbox" > {vm.States.map((state, i) => <label key={i}><input type="radio" value={state} checked={state.intValue===vm.PersonalState.intValue} onChange={this.handleOptionChange.bind(this,state)}/> <span>{state.displayName}</span></label>)} </div> </div> </form> <div> {vm.Count} </div> <div className="list-group"> Skills {vm.Skills.map((object, i) => <Skill skill={object} removeSkill={vm.RemoveSkill} key={i} id={i}>{object.Name} - {object.Type}</Skill>)} </div> <CommandButton command={vm.Command} name="Add Skill"></CommandButton> </div> ); } }
app/javascript/mastodon/components/radio_button.js
abcang/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class RadioButton extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, checked: PropTypes.bool, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, label: PropTypes.node.isRequired, }; render () { const { name, value, checked, onChange, label } = this.props; return ( <label className='radio-button'> <input name={name} type='radio' value={value} checked={checked} onChange={onChange} /> <span className={classNames('radio-button__input', { checked })} /> <span>{label}</span> </label> ); } }
fields/types/color/ColorField.js
Pop-Code/keystone
import { SketchPicker } from 'react-color'; import { css } from 'glamor'; import Field from '../Field'; import React from 'react'; import { Button, FormInput, InlineGroup as Group, InlineGroupSection as Section, } from '../../../admin/client/App/elemental'; import transparentSwatch from './transparent-swatch'; import coloredSwatch from './colored-swatch'; import theme from '../../../admin/client/theme'; const ColorField = Field.create({ displayName: 'ColorField', statics: { type: 'Color', }, propTypes: { onChange: React.PropTypes.func, path: React.PropTypes.string, value: React.PropTypes.string, }, getInitialState () { return { displayColorPicker: false, }; }, updateValue (value) { this.props.onChange({ path: this.props.path, value: value, }); }, handleInputChange (event) { var newValue = event.target.value; if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) { newValue = '#' + newValue; } if (newValue === this.props.value) return; this.updateValue(newValue); }, handleClick () { this.setState({ displayColorPicker: !this.state.displayColorPicker }); }, handleClose () { this.setState({ displayColorPicker: false }); }, handlePickerChange (color) { var newValue = color.hex; if (newValue === this.props.value) return; this.updateValue(newValue); }, renderSwatch () { const className = `${css(classes.swatch)} e2e-type-color__swatch`; return (this.props.value) ? ( <span className={className} style={{ color: this.props.value }} dangerouslySetInnerHTML={{ __html: coloredSwatch }} /> ) : ( <span className={className} dangerouslySetInnerHTML={{ __html: transparentSwatch }} /> ); }, renderField () { const { displayColorPicker } = this.state; return ( <div className="e2e-type-color__wrapper" style={{ position: 'relative' }}> <Group> <Section grow> <FormInput autoComplete="off" name={this.getInputName(this.props.path)} onChange={this.valueChanged} ref="field" value={this.props.value} /> </Section> <Section> <Button onClick={this.handleClick} cssStyles={classes.button} data-e2e-type-color__button> {this.renderSwatch()} </Button> </Section> </Group> {displayColorPicker && ( <div> <div className={css(classes.blockout)} data-e2e-type-color__blockout onClick={this.handleClose} /> <div className={css(classes.popover)} onClick={e => e.stopPropagation()} data-e2e-type-color__popover> <SketchPicker color={this.props.value} onChangeComplete={this.handlePickerChange} onClose={this.handleClose} /> </div> </div> )} </div> ); }, }); /* eslint quote-props: ["error", "as-needed"] */ const classes = { button: { background: 'white', padding: 4, width: theme.component.height, ':hover': { background: 'white', }, }, blockout: { bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1, }, popover: { marginTop: 10, position: 'absolute', left: 0, zIndex: 500, }, swatch: { borderRadius: 1, boxShadow: '0 0 0 1px rgba(0,0,0,0.1)', display: 'block', ' svg': { display: 'block', }, }, }; module.exports = ColorField;
admin/client/Signin/Signin.js
creynders/keystone
/** * The actual Sign In view, with the login form */ import assign from 'object-assign'; import classnames from 'classnames'; import React from 'react'; import xhr from 'xhr'; import Alert from './components/Alert'; import Brand from './components/Brand'; import UserInfo from './components/UserInfo'; import LoginForm from './components/LoginForm'; var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout', }; }, componentDidMount () { // Focus the email field when we're mounted if (this.refs.email) { this.refs.email.select(); } }, handleInputChange (e) { // Set the new state when the input changes const newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); // If either password or mail are missing, show an error if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } xhr({ url: `${Keystone.adminPath}/api/session/signin`, method: 'post', json: { email: this.state.email, password: this.state.password, }, headers: assign({}, Keystone.csrf.header), }, (err, resp, body) => { if (err || body && body.error) { return body.error === 'invalid csrf' ? this.displayError('Something went wrong; please refresh your browser and try again.') : this.displayError('The email and password you entered are not valid.'); } else { // Redirect to where we came from or to the default admin path if (Keystone.redirect) { top.location.href = Keystone.redirect; } else { top.location.href = this.props.from ? this.props.from : Keystone.adminPath; } } }); }, /** * Display an error message * * @param {String} message The message you want to show */ displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message, }); setTimeout(this.finishAnimation, 750); }, // Finish the animation and select the email field finishAnimation () { // TODO isMounted was deprecated, find out if we need this guard if (!this.isMounted()) return; if (this.refs.email) { this.refs.email.select(); } this.setState({ isAnimating: false, }); }, render () { const boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating, }); return ( <div className="auth-wrapper"> <Alert isInvalid={this.state.isInvalid} signedOut={this.state.signedOut} invalidMessage={this.state.invalidMessage} /> <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> <Brand logo={this.props.logo} brand={this.props.brand} /> {this.props.user ? ( <UserInfo adminPath={Keystone.adminPath} signoutPath={`${Keystone.adminPath}/signout`} userCanAccessKeystone={this.props.userCanAccessKeystone} userName={this.props.user.name} /> ) : ( <LoginForm email={this.state.email} handleInputChange={this.handleInputChange} handleSubmit={this.handleSubmit} isAnimating={this.state.isAnimating} password={this.state.password} /> )} </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); }, }); module.exports = SigninView;
src/js/components/icons/base/Brush.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-brush`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'brush'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M10.4350288,13.8510725 C8.66912406,14.6226292 7.43502884,16.3847098 7.43502884,18.4350288 C7.43502884,21.1964526 12.4350288,25.4350288 12.4350288,25.4350288 C12.4350288,25.4350288 17.4350288,21.1964526 17.4350288,18.4350288 C17.4350288,16.3847098 16.2009336,14.6226292 14.4350288,13.8510725 L14.4350288,-0.564864977 C14.4350288,-1.67491274 13.5395983,-2.56497116 12.4350288,-2.56497116 C11.3227585,-2.56497116 10.4350288,-1.66949312 10.4350288,-0.564864977 L10.4350288,13.8510725 Z M10,12 L12.6000977,12 L15,12" transform="rotate(45 12.435 11.435)"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Brush'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/components/Loader.js
cdiezmoran/AlphaStage-2.0
import React from 'react'; import styles from './Loader.scss'; const Loader = () => ( <div className={styles.BouncingLoader}> <div /> <div /> <div /> </div> ); export default Loader;
demo/src/App.js
alsiola/react-doc-props
import React, { Component } from 'react'; import CodeMirror from 'react-codemirror'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/lib/codemirror.css'; import { generateDocs } from 'react-doc-props'; import { documentation } from './PropDemo'; const documentationString = ` import { string, number, shape, arrayOf, setComponentProps } from 'react-doc-props'; export const documentation = { name: 'PropDemo', description: 'A component with some demo props.', props: { username: { type: string, description: 'The users name', default: 'Name not set' }, age: { type: number, description: 'Users age' }, post: { description: 'A blog post', type: shape.isRequired({ content: { type: string.isRequired, description: 'The content of the post' }, likes: { type: number.isRequired, description: 'How many people liked the post' }, category: { type: shape({ name: { type: string, description: 'The name of the category' }, id: { type: number, description: 'The id of the category' } }), description: 'The category of the blog post' } }) }, friends: { type: arrayOf({ description: 'A user', type: shape({ id: { type: number, description: 'The users id' }, name: { type: string, description: 'The users name' } }) }), description: 'An array of the users friends', default: [] } } } setComponentProps(documentation, PropDemo); `; const propTypesString = ` import PropTypes from 'prop-types'; PropDemo.propTypes = { username: PropTypes.string, age: PropTypes.number, post: PropTypes.shape({ content: PropTypes.string.isRequired, likes: PropTypes.number.isRequired, category: PropTypes.shape({ name: PropTypes.string, number: PropTypes.number }) }).isRequired, friends: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number, name: PropTypes.string }) ) }; PropDemo.defaultProps = { username: 'Name not set', friends: [] }; ` class App extends Component { render() { return ( <div className="App"> <h1>react-doc-props</h1> <p>This documentation object...</p> <CodeMirror value={documentationString} options={{ mode: 'javascript', readOnly: 'true' }} /> <p>...will generate this JSON...</p> <CodeMirror value={JSON.stringify(generateDocs(documentation), null, 4)} options={{ mode: 'javascript', readOnly: 'true' }} /> <p>...and is equivalent to the following...</p> <CodeMirror value={propTypesString} options={{ mode: 'javascript', readOnly: 'true' }} /> </div> ); } } export default App
docs/src/app/components/pages/components/Card/ExampleExpandable.js
verdan/material-ui
import React from 'react'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; const CardExampleExpandable = () => ( <Card> <CardHeader title="Without Avatar" subtitle="Subtitle" actAsExpander={true} showExpandableButton={true} /> <CardActions> <FlatButton label="Action1" /> <FlatButton label="Action2" /> </CardActions> <CardText expandable={true}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. </CardText> </Card> ); export default CardExampleExpandable;
tests/flow/react/createElementRequiredProp_string.js
arijs/prettier-miscellaneous
// @flow import React from 'react'; class Bar extends React.Component { props: { test: number, }; render() { return ( <div> {this.props.test} </div> ) } } class Foo extends React.Component { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }
src/svg-icons/device/battery-charging-30.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging30 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z"/> </SvgIcon> ); DeviceBatteryCharging30 = pure(DeviceBatteryCharging30); DeviceBatteryCharging30.displayName = 'DeviceBatteryCharging30'; DeviceBatteryCharging30.muiName = 'SvgIcon'; export default DeviceBatteryCharging30;
frontend/src/index.js
GaxZE/garyhawes.co.uk
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
src/js/components/_threads/ThreadNoResults.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import translate from '../../i18n/Translate'; import Button from '../ui/Button'; import * as ThreadActionCreators from '../../actions/ThreadActionCreators'; @translate('ThreadNoResults') export default class ThreadNoResults extends Component { static propTypes = { threadId: PropTypes.number.isRequired, deleting: PropTypes.bool, // Injected by @translate: strings : PropTypes.object }; static contextTypes = { router: PropTypes.object.isRequired }; constructor(props) { super(props); this.onDelete = this.onDelete.bind(this); this.onEdit = this.onEdit.bind(this); this.state = { deleting: null }; } onEdit() { this.context.router.push(`edit-thread/${this.props.threadId}`) } onDelete() { const {threadId} = this.props; ThreadActionCreators.deleteThread(threadId); } render() { const {threadId, deleting, strings} = this.props; const deleteText = deleting ? strings.deleting : strings.delete; return ( <div key={threadId} className="no-results-thread"> <div className="sub-title">{strings.emptyThread}</div> <div className="no-results-thread-buttons"> <Button onClick={this.onEdit} disabled={deleting ? 'disabled' : null}>{strings.edit}</Button> <Button onClick={this.onDelete} disabled={deleting ? 'disabled' : null}>{deleteText}</Button> </div> </div> ); } } ThreadNoResults.defaultProps = { strings: { emptyThread: 'This yarn is empty. Edit or delete it.', edit : 'Edit', delete : 'Delete', deleting : 'Deleting' } };
admin/client/Signin/Signin.js
jacargentina/keystone
/** * The actual Sign In view, with the login form */ import assign from 'object-assign'; import classnames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import xhr from 'xhr'; import Alert from './components/Alert'; import Brand from './components/Brand'; import UserInfo from './components/UserInfo'; import LoginForm from './components/LoginForm'; var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout', }; }, componentDidMount () { // Focus the email field when we're mounted if (this.refs.email) { ReactDOM.findDOMNode(this.refs.email).select(); } }, handleInputChange (e) { // Set the new state when the input changes const newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); // If either password or mail are missing, show an error if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } xhr({ url: `${Keystone.adminPath}/api/session/signin`, method: 'post', json: { email: this.state.email, password: this.state.password, }, headers: assign({}, Keystone.csrf.header), }, (err, resp, body) => { if (err || body && body.error) { return body.error === 'invalid csrf' ? this.displayError('Something went wrong; please refresh your browser and try again.') : this.displayError('The email and password you entered are not valid.'); } else { // Redirect to where we came from or to the default admin path if (Keystone.redirect) { top.location.href = Keystone.redirect; } else { top.location.href = this.props.from ? this.props.from : Keystone.adminPath; } } }); }, /** * Display an error message * * @param {String} message The message you want to show */ displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message, }); setTimeout(this.finishAnimation, 750); }, // Finish the animation and select the email field finishAnimation () { // TODO isMounted was deprecated, find out if we need this guard if (!this.isMounted()) return; if (this.refs.email) { ReactDOM.findDOMNode(this.refs.email).select(); } this.setState({ isAnimating: false, }); }, render () { const boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating, }); return ( <div className="auth-wrapper"> <Alert isInvalid={this.state.isInvalid} signedOut={this.state.signedOut} invalidMessage={this.state.invalidMessage} /> <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> <Brand logo={this.props.logo} brand={this.props.brand} /> <UserInfo user={this.props.user} userCanAccessKeystone={this.props.userCanAccessKeystone} /> <LoginForm user={this.props.user} handleSubmit={this.handleSubmit} handleInputChange={this.handleInputChange} email={this.state.email} password={this.state.password} animating={this.state.animating} /> </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); }, }); module.exports = SigninView;
src/index.js
zenoamaro/webpage-transcriber
import FastClick from 'fastclick'; import React from 'react'; import ReactDOM from 'react-dom'; import Root from 'views/Root'; import isMobile from 'utils/isMobile'; import scrape from 'scraper'; import spec from 'spec'; /** * Bootstrap the scraper and the template renderer * after doing some prep work. */ function bootstrap() { // Scrape the page at this time, and convert it // to a purer data representation. const payload = scrape(spec); // We create a root node for our application, // so that we aren't influenced by listeners // or other code that wants to touch <body>. const rootNode = document.createElement('div'); document.body.innerHTML = ''; document.body.appendChild(rootNode); // We want at least a viewport meta tag, so that we // are able to optimize the content for the viewport. const viewportNode = document.createElement('meta'); viewportNode.setAttribute('name', 'viewport'); viewportNode.setAttribute('content', 'width=device-width, user-scalable=no'); document.head.appendChild(viewportNode); // Adopt fast-click to remove the annoying // 300ms wait on clicks on iPhones. FastClick.attach(document.body); ReactDOM.render(<Root payload={payload}/>, rootNode); } /* We only want to operate when we have detected a mobile phone. We wouldn't want a bug ruining an otherwise working mission-critical app. */ if (isMobile()) bootstrap();
src/components/billing/transactions-list.js
Storj/metadisk-gui
import React from 'react'; import Currency from 'components/billing/currency'; const TransactionsList = ({ transactions }) => { return ( <section id="TransactionsListSection"> <div className="container"> <div className="row"> <div className="col-xs-12"> <h2 className="title">Billing History</h2> </div> </div> <div className="row"> <div className="col-xs-12"> <div className="table-responsive content"> <table className="table table-hover"> <thead> <tr> <th>Date</th> <th>Description</th> <th>Amount</th> </tr> </thead> <tbody> { transactions.map((transaction) => { const isNegative = (transaction.amount < 0); return ( <tr key={transaction.id} className="clickable-row"> <td> {transaction.created} </td> <td> {transaction.description} {!transaction.descriptionSub ? <span></span> : <span> <br /> <sub>{transaction.descriptionSub}</sub> </span> } </td> <td> <span className={isNegative ? 'text-success' : ''}> {isNegative ? '-' : ''} <Currency amount={isNegative ? -transaction.amount : transaction.amount} /> </span> </td> </tr> ); }) } </tbody> </table> </div> </div> </div> </div> </section> ); }; export default TransactionsList;
packages/examples-todomvc-metareducer/containers/Root.dev.js
kastigar/borex
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import TodoApp from './TodoApp'; import DevTools from './DevTools'; export default class Root extends Component { render() { const { store } = this.props; return ( <Provider store={store}> <div> <TodoApp /> <DevTools /> </div> </Provider> ); } }
src/InputSomething.js
frostney/react-lib-starterkit
import React from 'react'; const InputSomething = () => <input />; export default InputSomething;
node_modules/react-slick/src/track.js
prodigalyijun/demo-by-antd
'use strict'; import React from 'react'; import assign from 'object-assign'; import classnames from 'classnames'; var getSlideClasses = (spec) => { var slickActive, slickCenter, slickCloned; var centerOffset, index; if (spec.rtl) { index = spec.slideCount - 1 - spec.index; } else { index = spec.index; } slickCloned = (index < 0) || (index >= spec.slideCount); if (spec.centerMode) { centerOffset = Math.floor(spec.slidesToShow / 2); slickCenter = (index - spec.currentSlide) % spec.slideCount === 0; if ((index > spec.currentSlide - centerOffset - 1) && (index <= spec.currentSlide + centerOffset)) { slickActive = true; } } else { slickActive = (spec.currentSlide <= index) && (index < spec.currentSlide + spec.slidesToShow); } return classnames({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned }); }; var getSlideStyle = function (spec) { var style = {}; if (spec.variableWidth === undefined || spec.variableWidth === false) { style.width = spec.slideWidth; } if (spec.fade) { style.position = 'relative'; style.left = -spec.index * spec.slideWidth; style.opacity = (spec.currentSlide === spec.index) ? 1 : 0; style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; } return style; }; var getKey = (child, fallbackKey) => { // key could be a zero return (child.key === null || child.key === undefined) ? fallbackKey : child.key; }; var renderSlides = function (spec) { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var count = React.Children.count(spec.children); React.Children.forEach(spec.children, (elem, index) => { let child; var childOnClickOptions = { message: 'children', index: index, slidesToScroll: spec.slidesToScroll, currentSlide: spec.currentSlide }; if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) { child = elem; } else { child = (<div></div>); } var childStyle = getSlideStyle(assign({}, spec, {index: index})); var slickClasses = getSlideClasses(assign({index: index}, spec)); var cssClasses; if (child.props.className) { cssClasses = classnames(slickClasses, child.props.className); } else { cssClasses = slickClasses; } const onClick = function(e) { child.props && child.props.onClick && child.props.onClick(e) if (spec.focusOnSelect) { spec.focusOnSelect(childOnClickOptions) } } slides.push(React.cloneElement(child, { key: 'original' + getKey(child, index), 'data-index': index, className: cssClasses, tabIndex: '-1', style: assign({outline: 'none'}, child.props.style || {}, childStyle), onClick })); // variableWidth doesn't wrap properly. if (spec.infinite && spec.fade === false) { var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow; if (index >= (count - infiniteCount)) { key = -(count - index); preCloneSlides.push(React.cloneElement(child, { key: 'precloned' + getKey(child, key), 'data-index': key, className: cssClasses, style: assign({}, child.props.style || {}, childStyle), onClick })); } if (index < infiniteCount) { key = count + index; postCloneSlides.push(React.cloneElement(child, { key: 'postcloned' + getKey(child, key), 'data-index': key, className: cssClasses, style: assign({}, child.props.style || {}, childStyle), onClick })); } } }); if (spec.rtl) { return preCloneSlides.concat(slides, postCloneSlides).reverse(); } else { return preCloneSlides.concat(slides, postCloneSlides); } }; export class Track extends React.Component { render() { var slides = renderSlides.call(this, this.props); return ( <div className='slick-track' style={this.props.trackStyle}> { slides } </div> ); } }
codes/reactstrap-demo/src/components/Sidebar/Sidebar.js
atlantis1024/react-step-by-step
import React, { Component } from 'react'; import { Link } from 'react-router' class Sidebar extends Component { handleClick(e) { e.preventDefault(); e.target.parentElement.classList.toggle('open'); } activeRoute(routeName) { return this.props.location.pathname.indexOf(routeName) > -1 ? 'nav-item nav-dropdown open' : 'nav-item nav-dropdown'; } // secondLevelActive(routeName) { // return this.props.location.pathname.indexOf(routeName) > -1 ? "nav nav-second-level collapse in" : "nav nav-second-level collapse"; // } render() { return ( <div className="sidebar"> <nav className="sidebar-nav"> <ul className="nav"> <li className="nav-item"> <Link to={'/dashboard'} className="nav-link" activeClassName="active"><i className="icon-speedometer"></i> 报表 <span className="badge badge-info">NEW</span></Link> </li> <li className="nav-title"> UI 组件 </li> <li className={this.activeRoute("/components")}> <a className="nav-link nav-dropdown-toggle" href="#" onClick={this.handleClick.bind(this)}><i className="icon-puzzle"></i> 组件</a> <ul className="nav-dropdown-items"> <li className="nav-item"> <Link to={'/components/buttons'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 按钮</Link> </li> <li className="nav-item"> <Link to={'/components/social-buttons'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 社区按钮</Link> </li> <li className="nav-item"> <Link to={'/components/cards'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 卡片</Link> </li> <li className="nav-item"> <Link to={'/components/forms'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 表单</Link> </li> <li className="nav-item"> <Link to={'/components/modals'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 语气</Link> </li> <li className="nav-item"> <Link to={'/components/switches'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 开关</Link> </li> <li className="nav-item"> <Link to={'/components/tables'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 表格</Link> </li> <li className="nav-item"> <Link to={'/components/tabs'} className="nav-link" activeClassName="active"><i className="icon-puzzle"></i> 标签</Link> </li> </ul> </li> <li className={this.activeRoute("/icons")}> <a className="nav-link nav-dropdown-toggle" href="#" onClick={this.handleClick.bind(this)}><i className="icon-star"></i> 图标</a> <ul className="nav-dropdown-items"> <li className="nav-item"> <Link to={'/icons/font-awesome'} className="nav-link" activeClassName="active"><i className="icon-star"></i> Font Awesome 图标</Link> </li> <li className="nav-item"> <Link to={'/icons/simple-line-icons'} className="nav-link" activeClassName="active"><i className="icon-star"></i> 单行图标</Link> </li> </ul> </li> <li className="nav-item"> <Link to={'/widgets'} className="nav-link" activeClassName="active"><i className="icon-calculator"></i> 部件<span className="badge badge-info">NEW</span></Link> </li> <li className="nav-item"> <Link to={'/charts'} className="nav-link" activeClassName="active"><i className="icon-pie-chart"></i> 报表</Link> </li> <li className="divider"></li> <li className="nav-title"> 扩展 </li> <li className="nav-item nav-dropdown"> <a className="nav-link nav-dropdown-toggle" href="#" onClick={this.handleClick.bind(this)}><i className="icon-support"></i> 页面</a> <ul className="nav-dropdown-items"> <li className="nav-item"> <Link to={'/pages/login'} className="nav-link" activeClassName="active"><i className="icon-login"></i> 登录</Link> </li> <li className="nav-item"> <Link to={'/pages/register'} className="nav-link" activeClassName="active"><i className="icon-user"></i> 注册</Link> </li> <li className="nav-item"> <Link to={'/pages/404'} className="nav-link" activeClassName="active"><i className="icon-close"></i> Error 404</Link> </li> <li className="nav-item"> <Link to={'/pages/500'} className="nav-link" activeClassName="active"><i className="icon-close"></i> Error 500</Link> </li> </ul> </li> </ul> </nav> </div> ) } } export default Sidebar;
src/routes/teahouse/index.js
DiroKate/SysuhikerCC
import React from 'react'; import { connect } from 'dva'; import { browserHistory } from 'dva/router'; import { Tabs, Row, Col, Table, Modal } from 'antd'; import { CreateButton } from '../../components'; const { TabPane } = Tabs; function Teahouse({ isLogin, list, total, dispatch }) { const createHandler = () => { if (isLogin) { browserHistory.push('/bbs/create'); } else { Modal.warning({ title: '尚未登录', content: '报名活动需要先注册登录,跳转到登录页面?', iconType: 'meh-o', onOk() { browserHistory.push('/login'); }, }); } }; const onPageChange = (pagination) => { dispatch({ type: 'teahouse/getTopicList', payload: { page: pagination.current, pagesize: pagination.pageSize }, }); }; const rowClickHandler = (record) => { const { post_id: topicId } = record; browserHistory.push(`/bbs/${topicId}`); // TODO: 增加跳转到详细到帖子详情 }; const columns = [ { title: '类型', dataIndex: 'post_type', key: 'post_type', }, { title: '标题', dataIndex: 'post_title', key: 'post_title', }, { title: '作者', dataIndex: 'post_createUserNick', key: 'post_createUserNick', }, { title: '关键字', dataIndex: 'post_keywords', key: 'post_keywords', }, { title: '回复', dataIndex: 'post_countRe', key: 'post_countRe', }, { title: '最后更新', render: (text, record) => { const { post_modifyTime: updateTime, post_modifyUserNick: userNick } = record; return ( <p>{`${userNick || ''} 于 ${updateTime}`}</p> ); }, }]; const callback = (topic) => { dispatch({ type: 'teahouse/getTopicList', payload: { pagesize: 10, page: 1, post_type: topic, }, }); }; const TabData = { all: '全部', 作业攻略: '作业攻略', 技术讨论: '技术讨论', 活动讨论: '活动讨论', 户外安全: '户外安全', 其他: '其他', }; const tabChildren = Object.keys(TabData).map(key => ( <TabPane tab={TabData[key]} key={key} /> )); return ( <div className="sysuhiker-top-wrapper"> <Row gutter={24}> <Col xs={24} sm={18}> <Tabs defaultActiveKey="all" onChange={callback} animated={false}> {tabChildren} </Tabs> <Table dataSource={list} columns={columns} onChange={onPageChange} onRowClick={rowClickHandler} pagination={{ total, }} /> </Col> <Col xs={24} sm={6}> <CreateButton btnLabel="创建话题" createHandler={createHandler} alertLabel={{ message: '畅所欲言', description: '想灌水想发布攻略想寻求其他帮助?发个贴吧!', type: 'success', }} /> </Col> </Row> </div> ); } function mapStateToProps(state) { const { list, total } = state.teahouse; const { isLogin } = state.app; return { list, total, isLogin }; } export default connect(mapStateToProps)(Teahouse);
docs/app/Examples/elements/Button/Variations/ButtonExampleVerticallyAttached.js
mohammed88/Semantic-UI-React
import React from 'react' import { Button, Segment } from 'semantic-ui-react' const ButtonExampleVerticallyAttached = () => ( <div> <Button attached='top'>Top</Button> <Segment attached> <img src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Segment> <Button attached='bottom'>Bottom</Button> </div> ) export default ButtonExampleVerticallyAttached
DEPRECATED/node_modules/react-router/es6/IndexRedirect.js
vanHeemstraDesigns/CreationsEcosystemStatic
'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React, { Component } from 'react'; import Redirect from './Redirect'; import { falsy } from './PropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ var IndexRedirect = (function (_Component) { _inherits(IndexRedirect, _Component); function IndexRedirect() { _classCallCheck(this, IndexRedirect); _Component.apply(this, arguments); } /* istanbul ignore next: sanity check */ IndexRedirect.prototype.render = function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; }; return IndexRedirect; })(Component); IndexRedirect.propTypes = { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }; IndexRedirect.createRouteFromReactElement = function (element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : undefined; } }; export default IndexRedirect;
src/components/Card.js
nebgnahz/marry-guess
import React from 'react'; function Card(props) { return ( <div className="card"> <div className="image"> <img className="actual-image" src={props.image} role="presentation"/> <span className="title">{props.title}</span> </div> <div className="content"> <p>{props.content}</p> </div> </div> ) } Card.propTypes = { image: React.PropTypes.string.isRequired, title: React.PropTypes.string.isRequired, content: React.PropTypes.string.isRequired, link: React.PropTypes.string.isRequired, action: React.PropTypes.string.isRequired, enabled: React.PropTypes.bool, linkClicked: React.PropTypes.func, }; export default Card;
fields/types/location/LocationColumn.js
Ftonso/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country']; var LocationColumn = React.createClass({ displayName: 'LocationColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { let value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return null; let output = []; SUB_FIELDS.map((i) => { if (value[i]) { output.push(value[i]); } }); return ( <ItemsTableValue field={this.props.col.type} title={output.join(', ')}> {output.join(', ')} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = LocationColumn;
packages/@lyra/default-layout/src/components/SchemaErrors.js
VegaPublish/vega-studio
import React from 'react' import styles from './styles/SchemaErrors.css' import ErrorIcon from 'part:@lyra/base/error-icon' import WarningIcon from 'part:@lyra/base/warning-icon' import generateHelpUrl from '@lyra/generate-help-url' function renderPath(path) { return path .map(segment => { if (segment.kind === 'type') { return ( <span className={styles.segment}> <span key="name" className={styles.pathSegmentTypeName}> {segment.name} </span> &ensp; <span key="type" className={styles.pathSegmentTypeType}> {segment.type} </span> </span> ) } if (segment.kind === 'property') { return ( <span className={styles.segment}> <span className={styles.pathSegmentProperty}>{segment.name}</span> </span> ) } if (segment.kind === 'type') { return ( <span className={styles.segment}> <span key="name" className={styles.pathSegmentTypeName}> {segment.name} </span> <span key="type" className={styles.pathSegmentTypeType}> {segment.type} </span> </span> ) } return null }) .filter(Boolean) } export function SchemaErrors(props) { const {problemGroups} = props return ( <div className={styles.root}> <h2 className={styles.title}>Uh oh… found errors in schema</h2> <ul className={styles.list}> {problemGroups.map((group, i) => { return ( <li key={i} className={styles.listItem}> <h2 className={styles.path}>{renderPath(group.path)}</h2> <ul className={styles.problems}> {group.problems.map((problem, j) => ( <li key={j} className={styles[`problem_${problem.severity}`]}> <div className={styles.problemSeverity}> <span className={styles.problemSeverityIcon}> {problem.severity === 'error' && <ErrorIcon />} {problem.severity === 'warning' && <WarningIcon />} </span> <span className={styles.problemSeverityText}> {problem.severity} </span> </div> <div className={styles.problemContent}> <div className={styles.problemMessage}> {problem.message} </div> {problem.helpId && ( <a className={styles.problemLink} href={generateHelpUrl(problem.helpId)} target="_blank" > View documentation </a> )} </div> </li> ))} </ul> </li> ) })} </ul> </div> ) }
src/pages/linear.js
CentralCatholic/centralcatholic.github.io
import React from 'react' import Link from 'gatsby-link' import { Chart } from 'react-google-charts'; import BubbleData from '../data/bubble'; import FibData from '../data/fib'; import ExchangeData from '../data/exchange'; import LinearData from '../data/linear'; import BinaryData from '../data/binary'; class LinearChart extends React.Component { constructor(props) { super(props); this.state = { columns: [{ type: 'number', label: 'Input Size', }, { type: 'number', label: 'Duration (ms)', }], rows: LinearData, options: { title: 'Linear Sort', hAxis: { title: 'Array Size'}, vAxis: { title: 'Duration (ms)'}, legend: 'none', } } } render() { return ( <Chart chartType="ScatterChart" rows={this.state.rows} columns={this.state.columns} options={this.state.options} graph_id="ScatterChart" width={'100%'} height={'400px'} legend_toggle /> ); } } const BigOPage = () => ( <div> <h1>Linear Search</h1> <Link to="/">Go back to the homepage</Link> <LinearChart/> <Link to="/public/binary">Binary Search</Link> </div> ) export default BigOPage
internals/templates/containers/NotFoundPage/index.js
jdelatorreitrs/react-boilerplate
/** * 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/svg-icons/content/add-circle-outline.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAddCircleOutline = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ContentAddCircleOutline = pure(ContentAddCircleOutline); ContentAddCircleOutline.displayName = 'ContentAddCircleOutline'; ContentAddCircleOutline.muiName = 'SvgIcon'; export default ContentAddCircleOutline;
app/components/IssueIcon/index.js
perry-ugroop/ugroop-react-dup2
import React from 'react'; function IssueIcon(props) { return ( <svg height="1em" width="0.875em" className={props.className} > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } IssueIcon.propTypes = { className: React.PropTypes.string, }; export default IssueIcon;
src/svg-icons/device/location-disabled.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceLocationDisabled = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/> </SvgIcon> ); DeviceLocationDisabled = pure(DeviceLocationDisabled); DeviceLocationDisabled.displayName = 'DeviceLocationDisabled'; DeviceLocationDisabled.muiName = 'SvgIcon'; export default DeviceLocationDisabled;
react/CalendarIcon/CalendarIcon.js
seekinternational/seek-asia-style-guide
import svgMarkup from './CalendarIcon.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function CalendarIcon(props) { return <Icon markup={svgMarkup} {...props} />; } CalendarIcon.displayName = 'CalendarIcon';
lib/client/js/components/templates/templates-view.js
Bornholm/yasp
/* jshint esnext: true, node: true */ 'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import { connect } from 'react-redux'; import { Actions } from '../../store'; import FlexLayout from '../flex-layout'; import moment from 'moment'; import { translate } from 'react-i18next'; class TemplatesView extends React.Component { static select(state) { return { templates: state.templates }; } constructor() { super(); this.state = {}; this.handleRefreshClick = this.handleRefreshClick.bind(this); this.handleInstanciateClick = this.handleInstanciateClick.bind(this); } /* jshint ignore:start */ render() { let t = this.props.t; let templateGroups = this.groupByAppName(this.props.templates || []); let cardStyle = { margin: '10px 5px 0 0' }; let cards = Object.keys(templateGroups).map((appName, cardIndex) => { let templateVersions = templateGroups[appName]; let template = templateVersions[0]; let versionsOptions = templateVersions .sort((t1, t2) => { if(t1 === 'latest') return 1; if(t2 === 'latest') return -1; return t1.creationDate - t2.creationDate; }) .map(version => { return ( <option key={'template-version-'+version.tag} value={version.id}>{t(version.tag)}</option> ); }) ; return ( <div className="panel panel-default" key={template.id} style={cardStyle}> <div className="panel-heading"> <span><b>{template.appName}</b> - <small>{ moment(template.creationDate).calendar() }</small></span> </div> <div className="panel-body"> {template.appDescription} </div> <div className="panel-footer"> <form className="form-inline text-right" style={{margin: 0}}> <select ref={'templateVersionSelect-'+cardIndex} className="form-control input-sm"> {versionsOptions} </select> <button data-card-index={cardIndex} className="btn btn-primary btn-sm input-sm" onClick={this.handleInstanciateClick}> {t('instanciate')}<i className="fa inline-icon fa-plus"></i> </button> </form> </div> </div> ); }); return ( <div> <div className="clearfix"> <div className="btn-group pull-right" role="group"> <button className="btn btn-info btn-sm" onClick={this.handleRefreshClick}> {t('refresh')}<i className="fa fa-refresh inline-icon"></i> </button> </div> </div> <FlexLayout> {cards} </FlexLayout> </div> ); } /* jshint ignore:end */ componentWillMount() { this.props.dispatch(Actions.Apps.fetchTemplatesList()); } groupByAppName(templates) { return templates.reduce((grouped, template) => { if(!(template.appName in grouped)) { grouped[template.appName] = [template]; } else { grouped[template.appName].push(template); } return grouped; }, {}); } handleRefreshClick() { this.props.dispatch(Actions.Apps.fetchTemplatesList()); } handleInstanciateClick(evt) { evt.preventDefault(); let cardIndex = evt.currentTarget.dataset.cardIndex; let versionSelect = ReactDOM.findDOMNode(this.refs['templateVersionSelect-'+cardIndex]); let templateId = versionSelect.value; this.context.router.push(`/instanciate/${templateId}`); } } TemplatesView.contextTypes = { router: React.PropTypes.object }; export default translate(['templates-view'])(connect(TemplatesView.select)(TemplatesView));
docs/src/sections/ProgressBarSection.js
HPate-Riptide/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ProgressBarSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="progress">Progress bars</Anchor> <small>ProgressBar</small> </h2> <p className="lead">Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.</p> <h2><Anchor id="progress-basic">Basic example</Anchor></h2> <p>Default progress bar.</p> <ReactPlayground codeText={Samples.ProgressBarBasic} /> <h2><Anchor id="progress-label">With label</Anchor></h2> <p>Add a <code>label</code> prop to show a visible percentage. For low percentages, consider adding a min-width to ensure the label's text is fully visible.</p> <ReactPlayground codeText={Samples.ProgressBarWithLabel} /> <h2><Anchor id="progress-screenreader-label">Screenreader only label</Anchor></h2> <p>Add a <code>srOnly</code> prop to hide the label visually.</p> <ReactPlayground codeText={Samples.ProgressBarScreenreaderLabel} /> <h2><Anchor id="progress-contextual">Contextual alternatives</Anchor></h2> <p>Progress bars use some of the same button and alert classes for consistent styles.</p> <ReactPlayground codeText={Samples.ProgressBarContextual} /> <h2><Anchor id="progress-striped">Striped</Anchor></h2> <p>Uses a gradient to create a striped effect. Not available in IE8.</p> <ReactPlayground codeText={Samples.ProgressBarStriped} /> <h2><Anchor id="progress-animated">Animated</Anchor></h2> <p>Add <code>active</code> prop to animate the stripes right to left. Not available in IE9 and below.</p> <ReactPlayground codeText={Samples.ProgressBarAnimated} /> <h2><Anchor id="progress-stacked">Stacked</Anchor></h2> <p>Nest <code>&lt;ProgressBar /&gt;</code>s to stack them.</p> <ReactPlayground codeText={Samples.ProgressBarStacked} /> <h3><Anchor id="progress-props">ProgressBar</Anchor></h3> <PropTable component="ProgressBar"/> </div> ); }
client/components/Dashbord/favorite.js
kenware/more-recipes
import React, { Component } from 'react'; import { BrowserRouter, Route, Switch, Redirect, Link } from 'react-router-dom'; import { PropTypes } from 'react'; import * as actions from '../../redux/Action/action.js'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import './dashbord.scss'; import trim from '../trim'; import { Markup } from 'interweave'; class Favorite extends Component { constructor(props){ super(props) this.state = { message:"show" } } componentWillMount() { this.props.actions.loadMyFavoriteRecipes(); } render() { return ( <div className="col-sm-12"> <div className="card mb-4"> <div className="card-block"> <div className="card-header"> <h3 className="card-title">Favorite Recipes</h3> <div className="dropdown card-title-btn-container float-right"> <button className="btn btn-sm btn-subtle" type="button"><em className="fa fa-list-ul"></em> View All</button> <button className="btn btn-sm btn-subtle dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><em className="fa fa-cog"></em> </button> <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton"><a className="dropdown-item" href="#"><em className="fa fa-search mr-1"></em> More info</a> <a className="dropdown-item" href="#"><em className="fa fa-thumb-tack mr-1"></em> Pin Window</a> <a className="dropdown-item" href="#"><em className="fa fa-remove mr-1"></em> Close Window</a> </div> </div> <h6 className="card-subtitle mb-2 text-muted">My Favorite</h6> <h6 className="card-subtitle mb-2 text-muted">You have {this.props.FavoriteRecipes.length} Favorite recipe</h6> </div> <div className="divider" style={{marginTop: '1rem'}}></div> <div className="articles-container"> {this.props.FavoriteRecipes.map(recipe=> <div key={recipe.id} className="article border-bottom"> <div className="col-xs-12"> <div className="row"> <div className="col-3"> {recipe.createdAt} </div> <div className="col-2 date"> <a href={recipe.image}><img className="img-fluid rounded-circle card-img-top " src={recipe.image}/></a> </div> <div className="col-5"> <h4><Link to={`/dashbord/detail/${recipe.id}`}>{recipe.title}</Link></h4> <p className="card-text"> <Markup content={ trim.trim(`${recipe.content}`) + '...'} /> <Link to={`/dashbord/detail/${recipe.id}`}>View &rarr; </Link></p> </div> <div className="col-2"> <p><Link to={`/dashbord/detail/${recipe.id}`}>Edit/Delete </Link></p> </div> </div> <div className="alert alert-warning alert-dismissible" role="alert" id={`show`+ recipe.show}> <button type="button" className="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong> <span><font color='red'> Add favorite recipe<br/> <Link to={`/dashbord/detail/${recipe.id}`}> here </Link> </font> </span> </strong> </div> </div> <div className="clear"></div> </div> )} </div> </div> </div> </div> ); } } function mapStateToProps(state, ownProps) { return{ messageFavorite: state.message, FavoriteRecipes:state.favorite } } function mapDispatchToProps(dispatch) { return {actions: bindActionCreators(actions, dispatch)} } export default connect(mapStateToProps, mapDispatchToProps)(Favorite);
src/index.js
dopry/netlify-cms
import React from 'react'; import createReactClass from 'create-react-class'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import 'file-loader?name=index.html!../example/index.html'; import 'react-toolbox/lib/commons.scss'; import Root from './root'; import registry from './lib/registry'; import './index.css'; if (process.env.NODE_ENV !== 'production') { require('./utils.css'); // eslint-disable-line } // Log the version number console.log(`Netlify CMS version ${NETLIFY_CMS_VERSION}`); // Create mount element dynamically const el = document.createElement('div'); el.id = 'root'; document.body.appendChild(el); render(( <AppContainer> <Root /> </AppContainer> ), el); if (module.hot) { module.hot.accept('./root', () => { render(Root); }); } const buildtInPlugins = [{ label: 'Image', id: 'image', fromBlock: match => match && { image: match[2], alt: match[1], }, toBlock: data => `![${ data.alt }](${ data.image })`, toPreview: (data, getAsset) => <img src={getAsset(data.image)} alt={data.alt} />, pattern: /^!\[([^\]]+)]\(([^)]+)\)$/, fields: [{ label: 'Image', name: 'image', widget: 'image', }, { label: 'Alt Text', name: 'alt', }], }]; buildtInPlugins.forEach(plugin => registry.registerEditorComponent(plugin)); const CMS = {}; for (const method in registry) { // eslint-disable-line CMS[method] = registry[method]; } if (typeof window !== 'undefined') { window.CMS = CMS; window.createClass = window.createClass || createReactClass; window.h = window.h || React.createElement; } export default CMS;
src/GridList/GridList.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = { root: { display: 'flex', flexWrap: 'wrap', overflowY: 'auto', listStyle: 'none', padding: 0, }, }; function GridList(props) { const { cols, spacing, cellHeight, children, classes, className: classNameProp, component: ComponentProp, style, ...other } = props; return ( <ComponentProp className={classNames(classes.root, classNameProp)} style={{ margin: -spacing / 2, ...style }} {...other} > {React.Children.map(children, currentChild => { const childCols = currentChild.props.cols || 1; const childRows = currentChild.props.rows || 1; return React.cloneElement(currentChild, { style: Object.assign( { width: `${100 / cols * childCols}%`, height: cellHeight === 'auto' ? 'auto' : cellHeight * childRows + spacing, padding: spacing / 2, }, currentChild.props.style, ), }); })} </ComponentProp> ); } GridList.propTypes = { /** * Number of px for one cell height. * You can set `'auto'` if you want to let the children determine the height. */ cellHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['auto'])]), /** * Grid Tiles that will be in Grid List. */ children: PropTypes.node.isRequired, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Number of columns. */ cols: PropTypes.number, /** * The component used for the root node. * Either a string to use a DOM element or a component. * By default we map the type to a good default headline component. */ component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * Number of px for the spacing between tiles. */ spacing: PropTypes.number, /** * @ignore */ style: PropTypes.object, }; GridList.defaultProps = { cols: 2, spacing: 4, cellHeight: 180, component: 'ul', }; export default withStyles(styles, { name: 'MuiGridList' })(GridList);
src/CodeExample.js
joemcbride/react-playground
import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import {CodeMirror, IS_BROWSER} from './CodeMirrorSettings'; if (IS_BROWSER) { require('codemirror/addon/runmode/runmode'); } const propTypes = { codeText: React.PropTypes.string.isRequired, className: React.PropTypes.string, mode: React.PropTypes.string }; const defaultProps = { mode: 'javascript' }; class CodeExample extends React.Component { constructor(props) { super(props); this.update = this.update.bind(this); } componentDidMount() { this.update(); } componentDidUpdate() { this.update(); } update() { if (CodeMirror === undefined) { return; } CodeMirror.runMode( this.props.codeText, this.props.mode, ReactDOM.findDOMNode(this).children[0] ); } render() { let classes = classNames('code-example', 'CodeMirror', this.props.className); return ( <pre className={classes}> <code> {this.props.codeText} </code> </pre> ); } } CodeExample.defaultProps = defaultProps; CodeExample.propTypes = propTypes; export default CodeExample;
src/components/yii/plain-wordmark/YiiPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './YiiPlainWordmark.svg' /** YiiPlainWordmark */ function YiiPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'YiiPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } YiiPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default YiiPlainWordmark
frontend/src/components/partners/profile/overview/verification/partnerOverviewVerificationMenu.js
unicef/un-partner-portal
import PropTypes from 'prop-types'; import React from 'react'; import { withRouter } from 'react-router'; import DropdownMenu from '../../../../common/dropdownMenu'; import AddNewVerificationButton from '../../buttons/addNewVerificationButton'; import withDialogHandling from '../../../../common/hoc/withDialogHandling'; import AddVerificationModal from '../../modals/addVerificationModal/addVerificationModal'; const PartnerOverviewVerificationMenu = (props) => { const { params: { id }, dialogOpen, handleDialogClose, handleDialogOpen } = props; return ( <div> <DropdownMenu options={ [ { name: 'addNewVerification', content: <AddNewVerificationButton handleClick={() => handleDialogOpen()} />, }, ] } /> {dialogOpen && <AddVerificationModal partnerId={id} dialogOpen={dialogOpen} handleDialogClose={handleDialogClose} />} </div> ); }; PartnerOverviewVerificationMenu.propTypes = { params: PropTypes.object, dialogOpen: PropTypes.bool, handleDialogClose: PropTypes.func, handleDialogOpen: PropTypes.func, }; export default withDialogHandling(withRouter(PartnerOverviewVerificationMenu));