path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
pages/profile.js
vinaypuppal/linklet-app
import React from 'react' import NProgress from 'nprogress' import Header from '../components/Header' import FaGithub from 'react-icons/lib/fa/github' import FaSignOut from 'react-icons/lib/fa/sign-out' import ContainerPage from '../hocs/ContainerPage' import PublicPage from '../hocs/PublicPage' import { login, logout } from '../utils/authenticate' class Profile extends React.Component { render () { return ( <div className='Profile'> <Header user={this.props.user} url={this.props.url} title='Linklet | Profile' /> <main> <p className='info'> {this.props.url.query && this.props.url.query.next === '/my-links' ? 'Please login to view links added by you!...' : this.props.url.query && this.props.url.query.next === '/submit-link' ? 'Please login to submit new link' : this.props.url.query && this.props.url.query.next === '/bookmarks' ? 'Please login to view links bookmarked by you!..' : ''} </p> {this.props.isAuthenticated ? ( <div className='actual'> <div className='avatar'> <img src={`//images.weserv.nl/?url=${this.props.user.avatarUrl .replace('http://', '') .replace('https://', '')}&w=180&h=180&shape=circle`} alt={this.props.username} /> </div> <div className='username'>@{this.props.user.username}</div> {this.props.user.name && ( <div className='name'> <span className='label'>Name</span> <span className='value'>{this.props.user.name}</span> </div> )} {this.props.user.email && ( <div className='email'> <span className='label'>Email</span> <span className='value'>{this.props.user.email}</span> </div> )} <button onClick={() => { NProgress.start() logout() }} > <FaSignOut size={20} /> <span>LogOut</span> </button> </div> ) : ( <div className='dummy'> <div className='avatar' /> <div className='info'> <div className='name' /> <div className='links-shared' /> <div className='notifications' /> </div> <button onClick={() => { NProgress.start() login() }} > <FaGithub size={40} /> <span>Login With Github</span> </button> </div> )} </main> <style jsx> {` .Profile { min-height: 100%; width: 100%; } main { padding: 70px 20px 20px 20px; display: flex; align-items: center; justify-content: center; flex-direction: column; } p.info { font-weight: bold; } .dummy .avatar { width: 150px; height: 150px; border-radius: 50%; background: rgba(37, 53, 146, 0.1); margin: 10px auto; } .dummy .name, .dummy .links-shared, .dummy .notifications { width: 280px; height: 20px; background: rgba(37, 53, 146, 0.1); margin: 10px auto; border-radius: 4px; } .dummy .links-shared { width: 250px; } .dummy .notifications { width: 200px; } .actual .avatar img { border-radius: 50%; margin: 20px auto; } .actual .username { font-weight: 600; font-size: 24px; margin: 20px auto; } .actaul .name, .actual .email { margin: 20px auto; } .actual .label { margin-right: 20px; font-weight: bold; } button { width: 100%; margin: 50px 0; border: none; outline: none; -webkit-appearence: none; padding: 10px 20px; color: #fff; font-size: 16px; text-transform: uppercase; background: #222; border-radius: 4px; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); cursor: pointer; } button span { padding: 0 5px; } button:hover { background: #111; } .actual button { background: #f1f2f3; color: #222; font-size: 12px; padding: 10px; } .actual button:hover { background: rgba(37, 53, 146, 0.1); } @media (max-width: 720px) { main { padding-bottom: 60px; } .dummy .avatar, .dummy .name, .dummy .links-shared, .dummy .notifications { margin: 10px auto; } .dummy .avatar { width: 100px; height: 100px; } .dummy button { margin: 20px auto; } .actual .avatar { margin: 0 auto; text-align: center; } .actual .avatar img { margin: 0 auto 10px auto; width: 100px; height: 100px; } } `} </style> </div> ) } } export default ContainerPage(PublicPage(Profile))
client/app/components/playerList.js
dat2/hanabi-clone-web
import React from 'react' import Player from './player' class PlayerList extends React.Component { render() { let { players } = this.props return ( <div> { players.map((p, pI) => ( <Player key={pI} player={p} playerIndex={pI} /> )) } </div> ) } } PlayerList.defaultProps = { players: [] } export default PlayerList
pages/sass.js
murej/ansambel
import React from 'react' import './example.scss' import DocumentTitle from 'react-document-title' import { config } from 'config' export default class Sass extends React.Component { render () { return ( <DocumentTitle title={`${config.siteTitle} | Hi sassy friends`}> <div> <h1 className="the-sass-class" > Hi sassy friends </h1> <div className="sass-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> </DocumentTitle> ) } }
MobileApp/node_modules/react-native/local-cli/templates/HelloNavigation/views/welcome/WelcomeScreen.js
VowelWeb/CoinTradePros.com
'use strict'; import React, { Component } from 'react'; import { Image, Platform, StyleSheet, } from 'react-native'; import ListItem from '../../components/ListItem'; import WelcomeText from './WelcomeText'; export default class WelcomeScreen extends Component { static navigationOptions = { title: 'Welcome', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./welcome-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } render() { return ( <WelcomeText /> ); } } const styles = StyleSheet.create({ icon: { width: 30, height: 26, }, });
internals/templates/appContainer.js
jdm85kor/sentbe
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * 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'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
examples/todomvc/index.js
hetony/redux-devtools
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
frontend/src/containers/HomePage.js
OpenCollective/opencollective-website
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Numbro from 'numbro'; import 'numbro/dist/languages' import formatCurrency from '../lib/format_currency'; import i18n from '../lib/i18n'; import LoginTopBar from '../containers/LoginTopBar'; import MailChimpInputSection from '../components/homepage/MailChimpInputSection'; import PublicFooter from '../components/PublicFooter'; import CollectiveCard from '../components/CollectiveCard'; import fetchHome from '../actions/homepage/fetch'; export class HomePage extends Component { constructor(props) { super(props); this.state = { showSponsorMailInput: false }; } componentDidMount() { const { fetchHome, loadData} = this.props; if (loadData) { fetchHome(); } } render() { const { homepage, i18n } = this.props; const { showSponsorMailInput } = this.state; const currency = 'USD'; const opensource = homepage.collectives ? homepage.collectives.opensource : []; const meetup = homepage.collectives ? homepage.collectives.meetup : []; const sponsors = homepage.sponsors ? homepage.sponsors : []; const totalCollectives = homepage.stats ? homepage.stats.totalCollectives : 0; const totalAnnualBudget = homepage.stats ? homepage.stats.totalAnnualBudget : 0; const totalDonors = homepage.stats ? homepage.stats.totalDonors : 0; return ( <div className='HomePage'> <LoginTopBar /> <section className='HomePageHero'> <div className='title'> <svg width='500px' height='70px' className='align-middle'> <use xlinkHref='#svg-logotype' fill='#303233'/> </svg> </div> <div className='subtitle'>A new form of association, transparent by design</div> <div className='heading'>Open your finances to your community</div> </section> <section className='HomePageInfo' id='howitworks'> <div className='heading'>What is an open collective?</div> <div className='subheading'>A group of people with a shared mission that operates in full transparency</div> <div className='icons-container clearfix'> <div className='col sm-col-6 md-col-4'> <div className='-graphic -tghost'>&nbsp;</div> <div className='-heading'>Transparent</div> <div className='-description'>Anyone can follow the money.</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -oc'>&nbsp;</div> <div className='-heading'>Open</div> <div className='-description'>Anyone is welcome to join and contribute.</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -fluid'>&nbsp;</div> <div className='-heading'>Fluid</div> <div className='-description'>Leaders can change over time.</div> </div> </div> </section> <section className='HomePageOpenSource blue-gradient' id='opensource'> <div className='heading'>Collectives for <span className='color-blue'>Open Source</span> projects</div> <div className='subheading'>These open source projects have created open collectives to share their expenses and let their community chip in.</div> <div className='cards'> {opensource.map(group => <CollectiveCard key={group.id} i18n={i18n} group={group} />)} <a href='/opensource' className='seemore'>See more collectives</a> </div> <div className='cta'> <div className='text'>Have an open source project?</div> <a href='/opensource/apply'> <div className='button color-blue'>apply to create a collective!</div> </a> </div> </section> <section className='HomePageMeetups blue-gradient' id='meetups'> <div className='heading'>Collectives for <span className='color-green'>meetups</span></div> <div className='subheading'>Open Collective empowers local meetups to raise funds and have their own budget.</div> <div className='cards'> {meetup.map(group => <CollectiveCard key={group.id} i18n={i18n} group={group} />)} <a href='/discover?show=meetup' className='seemore'>See more meetups</a> </div> <div className='cta' id='apply'> <div className='text'>We are slowly letting in new kinds of collectives</div> <div className='button color-green'>join the waiting list!</div> </div> </section> <MailChimpInputSection mcListId='14d6233180' /> <section className='HomePageSponsors blue-gradient' id='sponsors'> <div className='heading'>Sponsors</div> <div className='subheading'>Great companies support great collectives with โค๏ธ</div> <div className='cards'> {sponsors.map(sponsor => <CollectiveCard key={sponsor.id} i18n={i18n} publicUrl={`/${sponsor.slug}`} isSponsor={true} group={sponsor} />)} </div> <div className='cta'> <div className='text'>Become a sponsor and support your community</div> <div className='button color-green' onClick={() => this.setState({showSponsorMailInput: !showSponsorMailInput})}>become a sponsor</div> </div> </section> {showSponsorMailInput && <MailChimpInputSection mcListId='4cbda7da19' buttonLabel='Apply' />} <section className='HomePageNumber'> <div className='heading'>Open Numbers</div> <div className='numbers-container'> <div className='clearfix'> <div className='col sm-col-6 md-col-4'> <div className='-graphic -tghost'> <div className='-value'>{Numbro(totalCollectives).format('0,0')}</div> </div> <div className='-heading'>Collectives</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -oc'> <div className='-value'>{Numbro(totalDonors).format('0,0')}</div> </div> <div className='-heading'>Backers</div> </div> <div className='col sm-col-6 md-col-4'> <div className='-graphic -fluid'> <div className='-value'>{formatCurrency(totalAnnualBudget, currency, { compact: true, precision: 0 })}</div> </div> <div className='-heading'>Annual budget</div> </div> </div> </div> </section> <PublicFooter /> </div> ) } } export default connect(mapStateToProps, { fetchHome })(HomePage); function mapStateToProps({ homepage, app}) { return { homepage, i18n: i18n('en'), loadData: app.rendered } }
src/client/home/components/FilterOptions/FilterOptions.js
noahamar/smlscrn
import R from 'ramda'; import React from 'react'; import classNames from 'classnames/bind'; import styles from './FilterOptions.styl'; const cx = classNames.bind(styles); export default class FilterOptions extends React.Component { constructor() { super(); } render() { const options = this.props.options || []; this.options = options .map(R.fromPairs) .map((item, i) => { return ( <option className={cx('FilterOptions__option')} key={item.id} value={item.id}> {item.label} </option>); }); return ( <div className={cx('FilterOptions')}> <select className={cx('FilterOptions__select')} onChange={this.props.onChange} value={this.props.selected}> { this.options } </select> <div className={cx('FilterOptions__triangle')}>&#9662;</div> </div> ); } }
src/components/Feedback/Feedback.js
lagache/e-voting-client
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright ยฉ 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.scss'; function Feedback() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit" >Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new" >Report an issue</a> </div> </div> ); } export default withStyles(Feedback, s);
react/features/base/components/buttons/QuickActionButton.js
jitsi/jitsi-meet
// @flow import { makeStyles } from '@material-ui/styles'; import React from 'react'; type Props = { /** * Label used for accessibility. */ accessibilityLabel: string, /** * Additional class name for custom styles. */ className: string, /** * Children of the component. */ children: string | React$Node, /** * Click handler. */ onClick: Function, /** * Data test id. */ testId?: string } const useStyles = makeStyles(theme => { return { button: { backgroundColor: theme.palette.action01, color: theme.palette.text01, borderRadius: `${theme.shape.borderRadius}px`, ...theme.typography.labelBold, lineHeight: `${theme.typography.labelBold.lineHeight}px`, padding: '8px 12px', display: 'flex', justifyContent: 'center', alignItems: 'center', border: 0, '&:hover': { backgroundColor: theme.palette.action01Hover } } }; }); const QuickActionButton = ({ accessibilityLabel, className, children, onClick, testId }: Props) => { const styles = useStyles(); return (<button aria-label = { accessibilityLabel } className = { `${styles.button} ${className}` } data-testid = { testId } onClick = { onClick }> {children} </button>); }; export default QuickActionButton;
examples/src/components/DisabledUpsellOptions.js
darrindickey/chc-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, onLabelClick: function (data, event) { console.log(data, event); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span>{option.label} {option.link} </span>; }, render: function() { var ops = [ { label: 'Basic customer support', value: 'basic' }, { label: 'Premium customer support', value: 'premium' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select onOptionLabelClick={this.onLabelClick} placeholder="Select your support level" options={ops} optionRenderer={this.renderOption} onChange={logChange} /> </div> ); } }); module.exports = DisabledUpsellOptions;
docs/src/pages/customization/TypographyTheme.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; function theme(outerTheme) { return createMuiTheme({ typography: { fontFamily: '-apple-system,system-ui,BlinkMacSystemFont,' + '"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif', body1: { fontWeight: outerTheme.typography.fontWeightMedium, }, button: { fontStyle: 'italic', }, }, }); } function TypographyTheme() { return ( <MuiThemeProvider theme={theme}> <div> <Typography type="body1">{'body1'}</Typography> <Button>{'Button'}</Button> </div> </MuiThemeProvider> ); } export default TypographyTheme;
src/index.js
ChronoBank/ChronoWAVES
import React from 'react'; import {Provider} from 'react-redux'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import injectTapEventPlugin from 'react-tap-event-plugin'; import './index.css'; import chronoTheme from './chrono-theme'; import store from './redux/store'; import router from './router'; import log from 'loglevel'; log.setLevel('debug'); // Needed for onTouchTap injectTapEventPlugin(); ReactDOM.render( <Provider store={store}> <MuiThemeProvider muiTheme={ chronoTheme }> {router} </MuiThemeProvider> </Provider>, document.getElementById('root') );
src/frontend/components/copyable.js
mweibel/esrscan-desktop
import React from 'react' import translation from './../translation' const {clipboard} = require('electron') export default class Copyable extends React.Component { constructor () { super() this.state = { 'copied': false } } onClick () { var text = this.props.textToCopy || this.props.text clipboard.writeText(text.trim()) this.setState({ copied: true }) } onMouseOut () { this.setState({ copied: false }) } render () { const onMouseOut = () => { this.onMouseOut() } const onClick = () => { this.onClick() } return ( <a onMouseOut={onMouseOut} onClick={onClick} className='copyable tooltip-link pos-rel dis-inline' href='#'> <span className='txt-grey prs'>{this.props.label}:</span> <span className='copyable-text'>{this.props.text}</span><i className='pls dis-hidden fa fa-clipboard'></i> <span className='mlm txt-small tooltip'>{this.state.copied ? translation.copied : translation.copyToClipboard}</span> </a> ) } } Copyable.propTypes = { text: React.PropTypes.string.isRequired, label: React.PropTypes.string.isRequired, // if not provided, this will be the text to copy textToCopy: React.PropTypes.string }
src/views/Card/CardMeta.js
shengnian/shengnian-ui-react
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, META, SUI, useTextAlignProp, } from '../../lib' /** * A card can contain content metadata. */ function CardMeta(props) { const { children, className, content, textAlign } = props const classes = cx( useTextAlignProp(textAlign), 'meta', className, ) const rest = getUnhandledProps(CardMeta, props) const ElementType = getElementType(CardMeta, props) return ( <ElementType {...rest} className={classes}> {childrenUtils.isNil(children) ? content : children} </ElementType> ) } CardMeta._meta = { name: 'CardMeta', parent: 'Card', type: META.TYPES.VIEW, } CardMeta.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** A card meta can adjust its text alignment. */ textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')), } export default CardMeta
docs/client.js
Cellule/react-bootstrap
import 'bootstrap/less/bootstrap.less'; import './assets/docs.css'; import './assets/style.css'; import './assets/carousel.png'; import './assets/logo.png'; import './assets/favicon.ico'; import './assets/thumbnail.png'; import './assets/thumbnaildiv.png'; import 'codemirror/mode/htmlmixed/htmlmixed'; import 'codemirror/mode/javascript/javascript'; import 'codemirror/theme/solarized.css'; import 'codemirror/lib/codemirror.css'; import './assets/CodeMirror.css'; import React from 'react'; import CodeMirror from 'codemirror'; import 'codemirror/addon/runmode/runmode'; import Router from 'react-router'; import routes from './src/Routes'; global.CodeMirror = CodeMirror; Router.run(routes, Router.RefreshLocation, Handler => { React.render( React.createElement(Handler, window.INITIAL_PROPS), document); });
src/components/Nav.js
limal/wolnik
import React from 'react'; import { Link } from 'gatsby'; export default function Nav({ onMenuToggle = () => {} }) { return ( <nav id="nav"> <ul> <li className="special"> <a href="#menu" onClick={e => { e.preventDefault(); onMenuToggle(); }} className="menuToggle" > <span>Menu</span> </a> <div id="menu"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/Generic">Generic Page</Link> </li> <li> <Link to="/Elements">Elements</Link> </li> </ul> <a className="close" onClick={e => { e.preventDefault(); onMenuToggle(); }} href="#menu" > {''} </a> </div> </li> </ul> </nav> ); }
src/Input.js
victorzhang17/react-bootstrap
import React from 'react'; import InputBase from './InputBase'; import * as FormControls from './FormControls'; import deprecationWarning from './utils/deprecationWarning'; class Input extends InputBase { render() { if (this.props.type === 'static') { deprecationWarning('Input type=static', 'StaticText'); return <FormControls.Static {...this.props} />; } return super.render(); } } Input.propTypes = { type: React.PropTypes.string }; export default Input;
src/components/TodoList.js
JarmoLaine/ModernWebDev
import React from 'react'; import Todo from './Todo'; const TodoList = ({ todos, onRemove, onToggle }) => <div> <h2>{todos.count()} items in my todo list</h2> <ul> {todos .map((todo, i) => <Todo key={i} onToggle={onToggle} onRemove={onRemove} todo={todo} /> ) } </ul> </div> export default TodoList;
src/main/index.js
tomaszkepa/san-antonio-tourist
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.getElementById('app'), );
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages } from 'react-intl'; import IconButton from '../../../components/icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import detectPassiveEvents from 'detect-passive-events'; import classNames from 'classnames'; const messages = defineMessages({ public_short: { id: 'privacy.public.short', defaultMessage: 'Public' }, public_long: { id: 'privacy.public.long', defaultMessage: 'Post to public timelines' }, unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' }, unlisted_long: { id: 'privacy.unlisted.long', defaultMessage: 'Do not show in public timelines' }, private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' }, private_long: { id: 'privacy.private.long', defaultMessage: 'Post to followers only' }, direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' }, direct_long: { id: 'privacy.direct.long', defaultMessage: 'Post to mentioned users only' }, change_privacy: { id: 'privacy.change', defaultMessage: 'Adjust status privacy' }, }); const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; class PrivacyDropdownMenu extends React.PureComponent { static propTypes = { style: PropTypes.object, items: PropTypes.array.isRequired, value: PropTypes.string.isRequired, placement: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } handleKeyDown = e => { const { items } = this.props; const value = e.currentTarget.getAttribute('data-index'); const index = items.findIndex(item => { return (item.value === value); }); let element; switch(e.key) { case 'Escape': this.props.onClose(); break; case 'Enter': this.handleClick(e); break; case 'ArrowDown': element = this.node.childNodes[index + 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'ArrowUp': element = this.node.childNodes[index - 1]; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'Home': element = this.node.firstChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; case 'End': element = this.node.lastChild; if (element) { element.focus(); this.props.onChange(element.getAttribute('data-index')); } break; } } handleClick = e => { const value = e.currentTarget.getAttribute('data-index'); e.preventDefault(); this.props.onClose(); this.props.onChange(value); } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem) this.focusedItem.focus(); this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } render () { const { mounted } = this.state; const { style, items, placement, value } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`privacy-dropdown__dropdown ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} role='listbox' ref={this.setRef}> {items.map(item => ( <div role='option' tabIndex='0' key={item.value} data-index={item.value} onKeyDown={this.handleKeyDown} onClick={this.handleClick} className={classNames('privacy-dropdown__option', { active: item.value === value })} aria-selected={item.value === value} ref={item.value === value ? this.setFocusRef : null}> <div className='privacy-dropdown__option__icon'> <i className={`fa fa-fw fa-${item.icon}`} /> </div> <div className='privacy-dropdown__option__content'> <strong>{item.text}</strong> {item.meta} </div> </div> ))} </div> )} </Motion> ); } } export default @injectIntl class PrivacyDropdown extends React.PureComponent { static propTypes = { isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onModalOpen: PropTypes.func, onModalClose: PropTypes.func, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: false, placement: 'bottom', }; handleToggle = ({ target }) => { if (this.props.isUserTouching()) { if (this.state.open) { this.props.onModalClose(); } else { this.props.onModalOpen({ actions: this.options.map(option => ({ ...option, active: option.value === this.props.value })), onClick: this.handleModalActionClick, }); } } else { const { top } = target.getBoundingClientRect(); this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); this.setState({ open: !this.state.open }); } } handleModalActionClick = (e) => { e.preventDefault(); const { value } = this.options[e.currentTarget.getAttribute('data-index')]; this.props.onModalClose(); this.props.onChange(value); } handleKeyDown = e => { switch(e.key) { case 'Escape': this.handleClose(); break; } } handleClose = () => { this.setState({ open: false }); } handleChange = value => { this.props.onChange(value); } componentWillMount () { const { intl: { formatMessage } } = this.props; this.options = [ { icon: 'globe', value: 'public', text: formatMessage(messages.public_short), meta: formatMessage(messages.public_long) }, { icon: 'unlock-alt', value: 'unlisted', text: formatMessage(messages.unlisted_short), meta: formatMessage(messages.unlisted_long) }, { icon: 'lock', value: 'private', text: formatMessage(messages.private_short), meta: formatMessage(messages.private_long) }, { icon: 'envelope', value: 'direct', text: formatMessage(messages.direct_short), meta: formatMessage(messages.direct_long) }, ]; } render () { const { value, intl } = this.props; const { open, placement } = this.state; const valueOption = this.options.find(item => item.value === value); return ( <div className={classNames('privacy-dropdown', placement, { active: open })} onKeyDown={this.handleKeyDown}> <div className={classNames('privacy-dropdown__value', { active: this.options.indexOf(valueOption) === 0 })}> <IconButton className='privacy-dropdown__value-icon' icon={valueOption.icon} title={intl.formatMessage(messages.change_privacy)} size={18} expanded={open} active={open} inverted onClick={this.handleToggle} style={{ height: null, lineHeight: '27px' }} /> </div> <Overlay show={open} placement={placement} target={this}> <PrivacyDropdownMenu items={this.options} value={value} onClose={this.handleClose} onChange={this.handleChange} placement={placement} /> </Overlay> </div> ); } }
js/components/inputgroup/regular.js
LetsBuildSomething/vmag_mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, Text, Body, Left, Right, Input, Item } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; const { popRoute, } = actions; class Regular extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Regular</Title> </Body> <Right /> </Header> <Content padder> <Item regular> <Input placeholder="Regular Textbox" /> </Item> </Content> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Regular);
src/Badge.js
15lyfromsaturn/react-materialize
import React from 'react'; import cx from 'classnames'; class Badge extends React.Component { render() { let { className, newIcon, children, ...props } = this.props; let classes = { badge: true, 'new': newIcon }; return ( <span className={cx(classes, className)} {...props}> {children} </span> ); } } Badge.propTypes = { /** * Add the <b>new</b> class name */ newIcon: React.PropTypes.bool }; export default Badge;
example/index.js
tether/react-download-ios
/** * Dependencies. */ import React from 'react' import ReactDOM from 'react-dom' import Badge from '..' /** * Render badge. */ ReactDOM.render( <Badge id="com.petrofeed.workidapp"/>, document.querySelector('main') )
client/src/components/SignupForm.js
richb-hanover/reactathon
import React from 'react'; import validator from 'validator'; import { FormErrors } from './partials'; import { Button, Input, ButtonInput } from 'react-bootstrap'; import { AppActions } from '../actions/AppActions'; import { AppStore } from '../stores/AppStore'; export class SignupForm extends React.Component { constructor() { super(); this.state = { ...AppStore.getState(), username: '', password: '', email: '' }; this.onChange = this.onChange.bind(this); } componentDidMount() { AppStore.listen(this.onChange); } componentWillUnmount() { AppStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } clearState = () => { this.setState({ username: '', password: '', email: '' }); }; handleUsernameChange = (e => this.onChange( {username: e.target.value}) ); handlePasswordChange = (e => this.onChange( {password: e.target.value}) ); handleEmailChange = (e => this.onChange( {email: e.target.value}) ); validate = () => { var errors = []; var { username, password, email } = this.state; const rules = [ { failOn: !validator.isEmail(email), error: 'Please use a valid email address' }, { failOn: username.trim().length < 4, error: 'Username must be at least 4 characters' }, { failOn: password.trim().length < 5, error: 'Password must be at least 5 characters' } ]; rules.forEach((rule) => { if (rule.failOn) { errors.push(rule); } }); if (errors.length) { return { errors: errors, valid: false }; } else { return { errors: null, valid: true }; } }; handleSubmit = (e) => { e.preventDefault(); var valid = this.validate(); if (valid.errors) { let article = valid.errors.length > 1 ? 'are' : 'is'; let noun = valid.errors.length > 1 ? 'errors' : 'error'; let count = valid.errors.length > 1 ? valid.errors.length : 'one'; this.setState({ error: { message: `There ${article} ${count} ${noun}, please try again.`, data: valid.errors } }); return; } AppActions.signup({ username: this.state.username, password: this.state.password, email: this.state.email }); }; render() { // handlers let { handleSubmit, handleUsernameChange, handlePasswordChange, handleEmailChange } = this; // state let { error, username, password, email } = this.state; return ( <section> {error ? <FormErrors {...error} /> : ''} <form onSubmit={handleSubmit}> <h4>Create an Account</h4> <hr/> <Input disabled={this.state.signupPending} type="text" label="Username" value={username} onChange={handleUsernameChange} placeholder="Enter a username" /> <Input disabled={this.state.signupPending} type="email" label="Email Address" value={email} onChange={handleEmailChange} placeholder="Enter email" /> <Input disabled={this.state.signupPending} type="password" value={password} onChange={handlePasswordChange} label="Password" /> {this.state.signupPending ? <Button disabled>Signing up...</Button> : <ButtonInput bsStyle="primary" type="submit" value="Signup" /> } </form> </section> ); } }
src/svg-icons/image/filter-center-focus.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterCenterFocus = (props) => ( <SvgIcon {...props}> <path d="M5 15H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4zM12 9c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ImageFilterCenterFocus = pure(ImageFilterCenterFocus); ImageFilterCenterFocus.displayName = 'ImageFilterCenterFocus'; ImageFilterCenterFocus.muiName = 'SvgIcon'; export default ImageFilterCenterFocus;
src/layouts/Card/CardLayout.js
armaanshah96/lunchbox
import React from 'react' import { IndexLink, Link } from 'react-router' import PropTypes from 'prop-types' import Avatar from 'material-ui/Avatar'; import Checkbox from 'material-ui/Checkbox'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import FileFolder from 'material-ui/FontIcon'; import { List, ListItem } from 'material-ui/List'; export const CardLayout = ({ id, children, check, name, details, selectedRestaurantId }) => { const avatar = <Avatar icon={<FileFolder />} />; const updateCheck = function(event, isInputChecked) { check(isInputChecked, id) } console.log(id, selectedRestaurantId) const checkbox = <Checkbox onCheck={updateCheck}/> const boom = ( <List> <ListItem leftCheckbox={ checkbox } rightAvatar={ avatar } primaryText={ name } secondaryText={ details } ></ListItem> </List> ) return ( <Card> <CardText children={ boom } /> </Card> ); } CardLayout.propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, details: PropTypes.string.isRequired, children: PropTypes.node, check: PropTypes.func.isRequired, selectedRestaurantId: PropTypes.string.isRequired } export default CardLayout
app/components/Pages/Team.js
alexpell00/FRCUltimateManager
/* * @Author: alexpelletier * @Date: 2016-03-23 22:17:30 * @Last Modified by: alexpelletier * @Last Modified time: 2016-03-24 05:44:31 */ import React from 'react'; import request from 'superagent'; import MatchesTable from '../Elements/MatchesTable' import PitStats from '../Elements/PitStats' import RobotStats from '../Elements/RobotStats' var Team = React.createClass({ getInitialState() { return {team:{}}; }, componentDidMount() { request .post('/Api/Teams/GetSingle') .send({'teamid':this.props.params.teamid}) .set('Accept', 'application/json') .end(function(err, res){ let team = JSON.parse(res.text); this.setState({ team: team }); }.bind(this)); }, render: function() { return ( <div className="content container"> <h2 className="page-title">Team <small></small></h2> <section className="widget"> <div className="row"> <div className="body col-sm-7"> <div className="row"> <div className="col-sm-4"> <div className="text-align-center"> <img className="img-circle" src="img/15.jpg" alt="64x64" style={{height: "112px"}}/> </div> </div> <div className="col-sm-8"> <h3 className="mt-sm mb-xs">{this.state.team.name}</h3> <address> <abbr title="">#</abbr>{this.state.team.number}<br/> <abbr title="">Location: </abbr>{this.state.team.location}<br/> <abbr title="">Website: </abbr><a href={this.state.team.website} target='_blank'>{this.state.team.website}</a><br/> </address> </div> </div> </div> </div> </section> <section className="widget widget-tabs"> <header> <ul className="nav nav-tabs"> <li className="active"> <a href="#matches" data-toggle="tab">Matches</a> </li> <li> <a href="#matchstats" data-toggle="tab">Match Stats</a> </li> <li> <a href="#robotstats" data-toggle="tab">Robot Stats</a> </li> <li> <a href="#pitstats" data-toggle="tab">Pit Stats</a> </li> </ul> </header> <div className="body tab-content"> <div id="matches" className="tab-pane active clearfix"> <MatchesTable teamid={this.props.params.teamid}/> </div> <div id="matchstats" className="tab-pane"> </div> <div id="robotstats" className="tab-pane"> <RobotStats teamid={this.props.params.teamid}/> </div> <div id="pitstats" className="tab-pane"> <PitStats teamid={this.props.params.teamid}/> </div> </div> </section> </div> ); } }); module.exports = Team;
src/components/docs/callout.js
nordsoftware/react-foundation-docs
import React from 'react'; import Playground from 'component-playground'; import { Colors, Sizes, Grid, Cell, Callout, } from 'react-foundation'; export const CalloutDocs = () => ( <section className="callout-docs"> <Grid> <Cell large={12}> <h2>Callout</h2> <div> <h3>Basics</h3> <Playground codeText={require('raw-loader!../examples/callout/basics').default} scope={{ React, Callout }} theme="eiffel"/> </div> <div> <h3>Coloring</h3> <Playground codeText={require('raw-loader!../examples/callout/colors').default} scope={{ React, Colors, Callout }} theme="eiffel"/> </div> <div> <h3>Sizing</h3> <Playground codeText={require('raw-loader!../examples/callout/sizes').default} scope={{ React, Sizes, Callout }} theme="eiffel"/> </div> </Cell> </Grid> </section> ); export default CalloutDocs;
submissions/leoasis/src/JediSlot.js
staltz/flux-challenge
import React from 'react'; export default class JediSlot extends React.Component { render() { const { jedi } = this.props; return <li className="css-slot"> {jedi && !jedi.fetching && <div style={jedi.isInCurrentPlanet ? { color: 'red' } : null}> <h3>{jedi.name}</h3> <h6>Homeworld: {jedi.homeworld.name}</h6> </div>} </li> } }
Console/app/node_modules/rc-slider/es/common/Track.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; /* eslint-disable react/prop-types */ import React from 'react'; var Track = function Track(props) { var className = props.className, included = props.included, vertical = props.vertical, offset = props.offset, length = props.length, style = props.style; var positonStyle = vertical ? { bottom: offset + '%', height: length + '%' } : { left: offset + '%', width: length + '%' }; var elStyle = _extends({ visibility: included ? 'visible' : 'hidden' }, style, positonStyle); return React.createElement('div', { className: className, style: elStyle }); }; export default Track;
docs/app/Examples/collections/Grid/Content/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const GridContentExamples = () => ( <ExampleSection title='Content'> <ComponentExample title='Rows' description='A row is a horizontal grouping of columns.' examplePath='collections/Grid/Content/GridExampleRows' /> <ComponentExample title='Columns' description='Columns each contain gutters giving them equal spacing from other columns.' examplePath='collections/Grid/Content/GridExampleColumns' /> </ExampleSection> ) export default GridContentExamples
src/client.js
MeetDay/dreampark-web
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { match, Router, browserHistory, applyRouterMiddleware } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect } from 'redux-async-connect' import { useScroll } from 'react-router-scroll'; import APIClient from './helpers/APIClient'; import createStore from './store'; import routes from './routes'; const client = new APIClient(); const store = createStore(browserHistory, client, window.__redux_data__); const history = syncHistoryWithStore(browserHistory, store); const userReduxConnect = () => ({ renderRouterContext: (child, props) => ( <ReduxAsyncConnect {...props} helpers={{ client, serverSide: false }} filter={item => item.deferred}> { child } </ReduxAsyncConnect> ) }); const dest = document.getElementById("app"); match({ history, routes: routes(store) }, (error, redirectLocation, renderProps) => { const component = ( <Provider store={store} key="provider"> <Router {...renderProps} history={history} render={ applyRouterMiddleware(useScroll(), userReduxConnect()) } /> </Provider> ); ReactDOM.render(component, dest); })
src/components/LoginForm/LoginForm.js
Nuriddinkhuja/photoshare
import React, { Component } from 'react'; import { reduxForm, propTypes, Field } from 'redux-form'; import { Form, Input, Button } from 'semantic-ui-react'; import loginValidation from './loginValidation'; @reduxForm({ form: 'login', validate: loginValidation }) export default class LoginForm extends Component { static propTypes = { ...propTypes } renderInput = ({ input, placeholder, type, meta: { touched, error } }) => { let errorText; if (error && touched) { errorText = error; } else { errorText = ''; } return <Input {...input} type={type} placeholder={placeholder} error={!!errorText} />; } render() { const { handleSubmit, error } = this.props; return ( <div className="ui middle aligned center aligned grid"> <div className="column"> <h2 className="ui white image header"> <div className="content"> Log-in to your account </div> </h2> {error && <p className="text-danger"><strong>{error}</strong></p>} <Form onSubmit={handleSubmit}> <div className="ui stacked segment"> <Form.Field > <div className="ui left icon input"> <i className="user icon"></i> <Field name="email" type="text" component={this.renderInput} placeholder="Email" /> </div> </Form.Field> <Form.Field > <div className="ui left icon input"> <i className="user icon"></i> <Field name="password" type="password" component={this.renderInput} placeholder="Password" /> </div> </Form.Field> <Button type="submit" className="fluid teal">Submit</Button> </div> </Form> </div> </div> ); } }
components/value_validation_component.js
KingHenne/react-common
import React from 'react'; import validate from '../utils/validate'; import validationStates from '../utils/validation_states'; // ValueValidationComponent is an abstract component. // The static props of this class will not be inherited on IE <= 10, // see: https://babeljs.io/docs/usage/caveats/#classes-10-and-below- export default class ValueValidationComponent extends React.Component { static validationProps = [ 'required', 'pattern', 'type', 'minAge', 'maxAge' ] state = { value: this.props.value, valid: this.props.value ? this.isValid(this.props.value) : undefined } componentDidMount() { if (this.props.onValidation) { // Send the initial valid state to the parent component. this.props.onValidation(this.props.name, this.state.valid, this.props.disabled); } } componentWillReceiveProps(nextProps) { if (nextProps.value != this.props.value && nextProps.value != this.state.value) { this.setState({ value: nextProps.value }, () => { this.validate(); }); } else if (nextProps.shouldValidate && !this.props.shouldValidate) { this.validate(true); } else if (nextProps.disabled != this.props.disabled && nextProps.onValidation) { nextProps.onValidation(nextProps.name, this.state.valid, nextProps.disabled); } } shouldComponentUpdate(nextProps, nextState) { // Ignore resetting of the validation request. if (nextProps.shouldValidate == false && this.props.shouldValidate) { return false; } return true; } // Can be override when other properties of target shall be used as value. getValueFromTarget(target) { return target.value; } handleChange(e) { var value = this.getValueFromTarget(e.target); this.setState({value}, () => { this.validate(); if (this.props.onChange) { this.props.onChange(value); } }); } handleBlur() { if (this.state.value) this.validate(true); } validate(alwaysChangeValidState = false) { var valid = this.isValid(this.state.value); var fromPendingToValid = this.state.valid == validationStates.PENDING && valid; var validChanged = this.state.valid != validationStates.PENDING && this.state.valid != valid; if (fromPendingToValid || validChanged || alwaysChangeValidState) { this.setState({valid}); if (this.props.onValidation) { this.props.onValidation(this.props.name, valid, this.props.disabled); } } return valid; } // Returns true (valid), false (invalid) or undefined (pending). isValid(value) { // Non-required fields with falsy values are valid, // regardless of their other validation props: if (!this.props.required && !value) return validationStates.VALID; // Otherwise every validation prop must be evaluated. return ValueValidationComponent.validationProps.every(function(prop) { if (prop in this.props) { return validate(prop, this.props[prop], value); } return validationStates.VALID; }, this); } }
app/components/PreviewExperimentComponent.js
openexp/OpenEXP
// @flow import React, { Component } from 'react'; import { Experiment } from 'jspsych-react'; import { Segment } from 'semantic-ui-react'; import callbackHTMLDisplay from '../utils/jspsych/plugins/callback-html-display'; import callbackImageDisplay from '../utils/jspsych/plugins/callback-image-display'; import { parseTimeline, instantiateTimeline, getImages } from '../utils/jspsych/functions'; import { MainTimeline, Trial, ExperimentParameters } from '../constants/interfaces'; interface Props { params: ExperimentParameters; isPreviewing: boolean; mainTimeline: MainTimeline; trials: { [string]: Trial }; timelines: {}; } export default class PreviewExperimentComponent extends Component<Props> { props: Props; handleTimeline: () => void; constructor(props: Props) { super(props); this.handleTimeline = this.handleTimeline.bind(this); } handleTimeline() { const timeline = instantiateTimeline( parseTimeline( this.props.params, this.props.mainTimeline, this.props.trials, this.props.timelines ), (value, time) => {}, // event callback () => {}, // start callback () => {}, // stop callback this.props.params.showProgessBar ); return timeline; } handleImages() { return getImages(this.props.params); } // This function could be used in the future in order to load custom pre-coded jspsych experiments // async handleCustomExperimentLoad() { // const timelinePath = await loadFromSystemDialog(FILE_TYPES.TIMELINE); // } render() { if (!this.props.isPreviewing) { return <Segment basic />; } return ( <Experiment settings={{ timeline: this.handleTimeline(), show_progress_bar: this.props.params.showProgessBar, auto_update_progress_bar: false, preload_images: this.handleImages() }} plugins={{ 'callback-image-display': callbackImageDisplay, 'callback-html-display': callbackHTMLDisplay }} /> ); } }
src/layouts/layout-5-1.js
nuruddeensalihu/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} </div> <div className="vertical"> {components[1]} {components[2]} {components[3]} {components[4]} </div> </div> );
src/components/PullRequest.js
nchaulet/bitbucket-team-pullrequests
import React from 'react'; import moment from 'moment'; import PullRequestDate from './PullRequestDate'; class PullRequest extends React.Component { render() { const {pr} = this.props; const avatarStyle = { marginRight: 10 }; const approved = pr.participants.reduce((sum, participant) => { return sum + (participant.approved ? 1 : 0); }, 0); const old = moment(pr.updated_on).diff(new Date()) * -1 / 1000 / 60 / 60 > 20; const statusClass = "bg-" + (approved ? 'success': 'info'); const pullRequestStyle = { padding: '10px', marginTop: 10, borderRadius: '4px', fontSize: '1.4em' }; const pullRequestTitleStyle = { fontSize: '1.1em', marginLeft: 40, }; return ( <div className={statusClass} style={pullRequestStyle}> <span className="pull-right small"> {approved != 0 ? ( <div><i className="fa fa-thumbs-o-up"></i> {approved}</div> ) : null} {approved != 0 ? ( <br/> ): null} {pr.commentsCount != 0 ? ( <div><i className="fa fa-comment-o"></i> {pr.commentsCount}</div> ) : null} </span> <img className="img-circle pull-left" style={avatarStyle} width="30" src={pr.author.links.avatar.href} /> <div style={pullRequestTitleStyle}> <a href={pr.links.html.href} target="_blank"> {pr.title} <br/> <small> {pr.source.repository.full_name} <br/><i className="fa fa-clock-o"></i> <PullRequestDate date={pr.updated_on}/> </small> </a> </div> <div className="clearfix" /> </div> ); } } export default PullRequest;
src/interface/ReportSelectionHeader.js
yajinni/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Trans } from '@lingui/macro'; import { ReactComponent as Logo } from 'interface/images/logo.svg'; import AlertWarning from 'interface/AlertWarning'; import { getReportHistory } from 'interface/selectors/reportHistory'; import NameSearch, { SearchType } from 'interface/NameSearch'; import ReportIcon from 'interface/icons/Events'; import CharacterIcon from 'interface/icons/Person'; import GuildIcon from 'interface/icons/People'; import ReportSelecter from './ReportSelecter'; import ReportHistory from './ReportHistory'; import './Header.scss'; const STATE_SEARCH_REPORT = 0; const STATE_SEARCH_CHAR = 1; const STATE_SEARCH_GUILD = 2; class ReportSelectionHeader extends React.PureComponent { static propTypes = { reportHistory: PropTypes.array.isRequired, }; constructor(props) { super(props); this.state = { searchType: STATE_SEARCH_REPORT, }; this.handleCharacterSearchClick = this.handleCharacterSearchClick.bind(this); this.handleReportSearchClick = this.handleReportSearchClick.bind(this); this.handleGuildSearchClick = this.handleGuildSearchClick.bind(this); } handleCharacterSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_CHAR, }); } handleReportSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_REPORT, }); } handleGuildSearchClick(e) { e.preventDefault(); this.setState({ searchType: STATE_SEARCH_GUILD, }); } renderSearch() { switch (this.state.searchType) { case STATE_SEARCH_CHAR: return ( <> <NameSearch type={SearchType.CHARACTER} /> <br /> <AlertWarning> <Trans id="interface.home.reportSelectionHeader.onlyRankedWCLogs"> The character page will only show fights that have been ranked by Warcraft Logs. Wipes are not included and during busy periods there might be a delay before new reports appear. You can still analyze these fights by manually finding the report on Warcraft Logs and using the report link. </Trans> </AlertWarning> </> ); case STATE_SEARCH_GUILD: return <NameSearch type={SearchType.GUILD} />; case STATE_SEARCH_REPORT: default: return <ReportSelecter />; } } render() { const { reportHistory } = this.props; return ( <header className="report-selection"> <div className="container"> <div className="row"> <div className={reportHistory.length !== 0 ? 'col-md-8' : 'col-md-12'}> <a href="/" className="brand-name"> <Logo /> <h1>WoWAnalyzer</h1> </a> <div id="reportSelectionHeader.improveYourPerformance"> <Trans id="interface.home.reportSelectionHeader.improveYourPerformance"> Improve your performance with personal feedback and stats. Just enter the link of a{' '} <a href="https://www.warcraftlogs.com/" target="_blank" rel="noopener noreferrer"> Warcraft Logs </a>{' '} report below. </Trans> </div> <div style={{ margin: '30px auto', maxWidth: 700, textAlign: 'left' }}> <nav> <ul> <li key="report" className={ this.state.searchType === STATE_SEARCH_REPORT ? 'active' : undefined } > <a href="/" style={{ padding: '5px' }} onClick={this.handleReportSearchClick}> <ReportIcon /> <Trans id="interface.home.reportSelectionHeader.report">Report</Trans> </a> </li> <li key="character" className={this.state.searchType === STATE_SEARCH_CHAR ? 'active' : undefined} > <a href="/" style={{ padding: '5px' }} onClick={this.handleCharacterSearchClick} > <CharacterIcon /> <Trans id="interface.home.reportSelectionHeader.character">Character</Trans> </a> </li> <li key="guild" className={ this.state.searchType === STATE_SEARCH_GUILD ? 'active' : undefined } > <a href="/" style={{ padding: '5px' }} onClick={this.handleGuildSearchClick}> <GuildIcon /> <Trans id="interface.home.reportSelectionHeader.guild">Guild</Trans> </a> </li> </ul> </nav> {this.renderSearch()} </div> </div> {reportHistory.length !== 0 && ( <div className="col-md-4 text-left" style={{ marginTop: -10, marginBottom: -10 }}> <small> <Trans id="interface.home.reportSelectionHeader.recentlyViewed"> Recently viewed </Trans> </small> <br /> <ReportHistory reportHistory={reportHistory} /> </div> )} </div> </div> </header> ); } } const mapStateToProps = (state) => ({ reportHistory: getReportHistory(state), }); export default connect(mapStateToProps)(ReportSelectionHeader);
packages/react/src/components/SecondaryButton/SecondaryButton.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import Button from '../Button'; const SecondaryButton = (props) => <Button kind="secondary" {...props} />; export default SecondaryButton;
app/js/todo/form.js
pengux/electron-react-starter
import React from 'react'; import TodoActions from './actions'; export default React.createClass({ create(e) { e.preventDefault(); var task = this.refs.newTask.value; TodoActions.create({"name": task}); }, render() { return ( <form onSubmit={this.create}> <label> Add task <input type="text" ref="newTask" /> </label> </form> ); } });
ui/src/common/BatchPlayButton.js
cloudsonic/sonic-server
import React from 'react' import PropTypes from 'prop-types' import { Button, useDataProvider, useTranslate, useUnselectAll, useNotify, } from 'react-admin' import { useDispatch } from 'react-redux' export const BatchPlayButton = ({ resource, selectedIds, action, label, icon, className, }) => { const dispatch = useDispatch() const translate = useTranslate() const dataProvider = useDataProvider() const unselectAll = useUnselectAll() const notify = useNotify() const addToQueue = () => { dataProvider .getMany(resource, { ids: selectedIds }) .then((response) => { // Add tracks to a map for easy lookup by ID, needed for the next step const tracks = response.data.reduce( (acc, cur) => ({ ...acc, [cur.id]: cur }), {} ) // Add the tracks to the queue in the selection order dispatch(action(tracks, selectedIds)) }) .catch(() => { notify('ra.page.error', 'warning') }) unselectAll(resource) } const caption = translate(label) return ( <Button aria-label={caption} onClick={addToQueue} label={caption} className={className} > {icon} </Button> ) } BatchPlayButton.propTypes = { action: PropTypes.func.isRequired, label: PropTypes.string.isRequired, icon: PropTypes.object.isRequired, }
app/react-icons/fa/copyright.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaCopyright extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m28.7 24v2.4q0 1.1-0.8 2t-2.1 1.3-2.7 0.8-2.6 0.2q-4.6 0-7.6-3.1t-3.1-7.7q0-4.5 3-7.6t7.6-3q0.7 0 1.7 0.1t2 0.4 2.1 0.7 1.6 1.3 0.6 1.8v2.4q0 0.4-0.4 0.4h-2.6q-0.4 0-0.4-0.4v-1.5q0-1-1.4-1.5t-3.1-0.6q-3.1 0-5.1 2.1t-2 5.3q0 3.3 2.1 5.5t5.2 2.2q1.5 0 3.1-0.5t1.5-1.5v-1.5q0-0.2 0.1-0.3t0.3-0.1h2.6q0.1 0 0.3 0.1t0.1 0.3z m-8.6-18.3q-2.9 0-5.5 1.2t-4.6 3-3 4.6-1.1 5.5 1.1 5.5 3 4.6 4.6 3 5.5 1.2 5.6-1.2 4.5-3 3.1-4.6 1.1-5.5-1.1-5.5-3.1-4.6-4.5-3.1-5.6-1.1z m17.2 14.3q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"/></g> </IconBase> ); } }
client/src/routes.js
Enter-36-chambers-of-wu-tang-fam/Ilera-health
// React import React from 'react'; import ReactDOM from 'react-dom'; // React Router import { Router, Route, IndexRoute } from 'react-router'; //Authentication Requirement import PhysicianAuth from './auth-shared/higher-order-components/physician_auth.jsx'; import PatientAuth from './auth-shared/higher-order-components/patient_auth.jsx'; import StaffAuth from './auth-shared/higher-order-components/staff_auth.jsx'; import GeneralAuth from './auth-shared/higher-order-components/general_auth.jsx'; //Shared Components import App from './main/app.js'; import Welcome from './auth-shared/components/landing-page/welcome.jsx'; import Signin from './auth-shared/components/signin-component.jsx'; import Signup from './auth-shared/components/signup-component.jsx'; import AllPhysicians from './patients/components/physicians-dash/allPhysicians.jsx'; import AllPhysicianProfile from './patients/components/physicians-dash/allPhysicianProfile.jsx' import Chat from './patients/containers/messages/chat-container.js'; // Physician Components import PhysicianApp from './physicians/physician-app/physician-app.jsx'; import ProviderAppFormContainer from './physicians/containers/onboarding/provider-signup-forms.jsx'; import PhysicianDashboard from './physicians/containers/main-dash/provider-dash.jsx'; import Notes from './physicians/physician-app/notes.jsx'; import Calendar from './physicians/physician-app/calendar.jsx'; import ProvPatProfile from './physicians/components/patient-ind-profile-dash/profile-main.jsx'; import AllUsers from './physicians/components/patients-dash/allUsers.jsx' import PhysProfile from './physicians/components/profile-dash/patient-profile.jsx'; // Patient Components import PatientApp from './patients/containers/patient-app.jsx'; import PatientDashboard from './patients/containers/main-dash/patient-dashboard.jsx'; import HealthLog from './patients/components/health-log-dash/health-log.jsx'; import Profile from './patients/components/profile-dash/patient-profile.jsx'; import Medication from './patients/containers/medication/medication-container.js'; import PhysicianCalendar from './patients/components/physicians-dash/physicianAppointment.jsx'; import PatientAppFormContainer from './patients/components/onboarding/patient-signup-forms.jsx'; import MedicalHistory from './patients/components/medical-history-dash/medical-history-dashboard.jsx'; import MedicalHistoryUpload from './patients/components/medical-history-dash/uploadDocuments.jsx'; import MedicalHistoryAppointment from './patients/components/medical-history-dash/appointment-history-dashboard.jsx'; // Staff Components import StaffApp from './staff/components/staff-app.jsx'; import StaffAppFormContainer from './staff/components/onboarding/staff-signup-forms.jsx'; import StaffDashboard from './staff/components/main-dash/staff-dashboard.jsx'; export default ( <Router path='/' component= { App } > <IndexRoute component={ GeneralAuth(Welcome) }/> <Route path='signup' component={ GeneralAuth(Signup) } /> <Route path='signin' component={ GeneralAuth(Signin) } /> <Route path='provider' component={ PhysicianAuth(PhysicianApp) } > <Route path="welcome" > <IndexRoute component={ ProviderAppFormContainer } /> </Route> <Route path="dashboard" component={ PhysicianDashboard } /> <Route path="/provider/patients" component={ AllUsers } /> <Route path='/provider/patients/:patientId' component={ ProvPatProfile } /> <Route path='test' component={ ProvPatProfile } /> <Route path="notes" component={ Notes } /> <Route path="messages" component={ Chat } /> <Route path="profile" component={ PhysProfile } /> <Route path="calendar" component ={ Calendar }/> </Route> <Route path='patient' component={ PatientAuth(PatientApp) } > <Route path="welcome" > <IndexRoute component={ PatientAppFormContainer } /> </Route> <Route path="dashboard" component={ PatientDashboard } /> <Route path="healthlog" component={ HealthLog } /> <Route path="physicians" component={ AllPhysicians } /> <Route path='physicians/:provider' component={ AllPhysicianProfile } > <Route path='individual' component={ PhysicianCalendar } /> </Route> <Route path="messages" component={ Chat } /> <Route path="profile" component={ Profile } /> <Route path="medications" component={ Medication } /> <Route path="records" component={ MedicalHistory } /> <Route path="records/upload" component={ MedicalHistoryUpload } /> <Route path="records/appointments" component={ MedicalHistoryAppointment } /> </Route> <Route path='staff' component={ StaffAuth(StaffApp) } > <Route path="form" > <IndexRoute component={ StaffAppFormContainer } /> </Route> <Route path="dashboard" component={ StaffDashboard } /> </Route> </Router> );
src/svg-icons/image/burst-mode.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBurstMode = (props) => ( <SvgIcon {...props}> <path d="M1 5h2v14H1zm4 0h2v14H5zm17 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z"/> </SvgIcon> ); ImageBurstMode = pure(ImageBurstMode); ImageBurstMode.displayName = 'ImageBurstMode'; ImageBurstMode.muiName = 'SvgIcon'; export default ImageBurstMode;
app/javascript/src/client/sessions/destroy.js
rringler/billtalk
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { destroySession } from './actions'; class SessionDestroy extends Component { componentWillMount() { this.props.destroySession(); this.props.history.push('/'); } render() { return <div></div>; } } export default connect(null, { destroySession })(SessionDestroy);
node_modules/react-bootstrap/es/NavbarBrand.js
C0deSamurai/muzjiks
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { prefix } from './utils/bootstrapUtils'; var contextTypes = { $bs_navbar: React.PropTypes.shape({ bsClass: React.PropTypes.string }) }; var NavbarBrand = function (_React$Component) { _inherits(NavbarBrand, _React$Component); function NavbarBrand() { _classCallCheck(this, NavbarBrand); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } NavbarBrand.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = prefix(navbarProps, 'brand'); if (React.isValidElement(children)) { return React.cloneElement(children, { className: classNames(children.props.className, className, bsClassName) }); } return React.createElement( 'span', _extends({}, props, { className: classNames(className, bsClassName) }), children ); }; return NavbarBrand; }(React.Component); NavbarBrand.contextTypes = contextTypes; export default NavbarBrand;
demo/src/mockups/calculator/interfaces/calculator-interface.js
tuantle/hypertoxin
'use strict'; // eslint-disable-line import { Hf } from 'hyperflow'; import { Ht } from 'hypertoxin'; import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import EVENT from '../events/calculator-event'; const KEYPADLABELS = [ [ `C`, `7`, `4`, `1`, `0` ], [ `ยฑ`, `8`, `5`, `2` ], [ `Pi`, `9`, `6`, `3`, `.` ], [ `รท`, `ร—`, `-`, `+`, `=` ] ]; const { BodyScreen, HeaderScreen, RowLayout, ColumnLayout, FlatButton, IconImage, HeadlineText, SubtitleText, CaptionText } = Ht; const CalculatorInterface = Hf.Interface.augment({ composites: [ Hf.React.ComponentComposite ], setup (done) { done(); }, render () { const component = this; const { navigation, screenProps } = component.props; const { Theme, shade } = screenProps.component.state; const { displayResult, displayComputes } = component.state; return ([ <HeaderScreen key = 'header-screen' shade = { shade } label = 'CALCULATOR APP' > <FlatButton room = 'content-left' overlay = 'transparent' corner = 'circular' onPress = {() => { component.outgoing(EVENT.ON.RESET).emit(); navigation.navigate(`mockupAppsHome`); }} > <IconImage room = 'content-middle' size = 'large' source = 'go-back' /> </FlatButton> </HeaderScreen>, <BodyScreen key = 'body-screen' shade = { shade } contentTopRoomAlignment = 'stretch' coverImageSource = { shade === `light` ? require(`../../../../assets/images/light-background-with-logo.png`) : require(`../../../../assets/images/dark-background-with-logo.png`) } > <ColumnLayout room = 'content-top' overlay = 'transparent-outline' roomAlignment = 'end' color = 'accent' corner = 'circular' margin = {{ top: 150, horizontal: 20, right: 10 }} > <HeadlineText room = 'content-right' size = 'large' indentation = { -10 } color = { Theme.color.palette.white }>{ displayResult }</HeadlineText> </ColumnLayout> <RowLayout room = 'content-middle' roomAlignment = 'stretch' margin = {{ horizontal: 20 }} > <RowLayout room = 'content-top' overlay = 'transparent' roomAlignment = 'end' margin = {{ bottom: 30 }} > <SubtitleText room = 'content-middle' size = 'small' color = { Theme.color.palette.grey }>{ `${displayComputes}` }</SubtitleText> <CaptionText room = 'content-middle' > Version: 0.6 </CaptionText> </RowLayout> <ColumnLayout room = 'content-middle' overlay = 'transparent' roomAlignment = 'start' margin = {{ horizontal: 40, bottom: 30 }} > { KEYPADLABELS.map((cellLabels, col) => { return ( <RowLayout key = { col } room = 'content-middle' overlay = 'transparent' roomAlignment = 'center' margin = {{ horizontal: 10 }} > { cellLabels.map((cellLabel, row) => { return ( <FlatButton room = 'content-middle' key = { cellLabel } label = { cellLabel } size = 'large' corner = 'round' overlay = 'opaque' color = {(() => { if (row === 0 && col < 3) { return `secondary`; } else if (col === 3) { return `accent`; } return `primary`; })()} onPress = {() => { if (cellLabel === `C`) { component.outgoing(EVENT.ON.RESET).emit(); } else if (cellLabel === `รท` || cellLabel === `ร—` || cellLabel === `+` || cellLabel === `-`) { component.outgoing(EVENT.ON.OPERATION).emit(() => cellLabel); } else if (Hf.isNumeric(cellLabel) || cellLabel === `.` || cellLabel === `Pi` || cellLabel === `ยฑ`) { component.outgoing(EVENT.ON.OPERAND).emit(() => cellLabel); } else if (cellLabel === `=`) { component.outgoing(EVENT.ON.COMPUTE).emit(); } }} /> ); }) } </RowLayout> ); }) } </ColumnLayout> </RowLayout> </BodyScreen> ]); } }); export default CalculatorInterface;
modules/dqt/jsx/react.notice.js
aces/Loris
import React from 'react'; const NoticeMessage = (props) => { let alert; // Display load alert if alert is present if (props.alertLoaded) { alert = ( <div className='alert alert-success' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <strong>Success</strong> Query Loaded. </div> ); } // Display save alert if alert is present if (props.alertSaved) { alert = ( <div className='alert alert-success' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <strong>Success</strong> Query Saved. </div> ); } // Display Conflict Query alert if (props.alertConflict.show) { alert = ( <div className='alert alert-warning' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>Override</span> </button> <strong>Error</strong> Query with the same name already exists. <a href='#' className='alert-link' onClick={props.overrideQuery}>Click here to override</a> </div> ); } return ( <> {alert} </> ); }; export default NoticeMessage;
src/components/common/svg-icons/image/monochrome-photos.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMonochromePhotos = (props) => ( <SvgIcon {...props}> <path d="M20 5h-3.2L15 3H9L7.2 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-8v-1c-2.8 0-5-2.2-5-5s2.2-5 5-5V7h8v12zm-3-6c0-2.8-2.2-5-5-5v1.8c1.8 0 3.2 1.4 3.2 3.2s-1.4 3.2-3.2 3.2V18c2.8 0 5-2.2 5-5zm-8.2 0c0 1.8 1.4 3.2 3.2 3.2V9.8c-1.8 0-3.2 1.4-3.2 3.2z"/> </SvgIcon> ); ImageMonochromePhotos = pure(ImageMonochromePhotos); ImageMonochromePhotos.displayName = 'ImageMonochromePhotos'; ImageMonochromePhotos.muiName = 'SvgIcon'; export default ImageMonochromePhotos;
src/demo/App.js
sergiocruz/react-logbook
import React, { Component } from 'react'; import { Link } from 'react-router'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h1>React Logbook</h1> <div className="App-intro"> <ul className="App-menu"> <li>Demos:</li> <li> <Link to="/inline" activeClassName="active">inline</Link> </li> <li> <Link to="/ajax" activeClassName="active">ajax</Link> </li> <li> <Link to="/firebase" activeClassName="active">firebase</Link> </li> </ul> </div> </div> <div className="container"> {this.props.children} </div> </div> ); } } export default App;
packages/material-ui-icons/src/DialerSip.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let DialerSip = props => <SvgIcon {...props}> <path d="M17 3h-1v5h1V3zm-2 2h-2V4h2V3h-3v3h2v1h-2v1h3V5zm3-2v5h1V6h2V3h-3zm2 2h-1V4h1v1zm0 10.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.01.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.27-.26.35-.65.24-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z" /> </SvgIcon>; DialerSip = pure(DialerSip); DialerSip.muiName = 'SvgIcon'; export default DialerSip;
client/src/components/setup-workflow/inprogress_lists.js
safv12/trello-metrics
'use strict'; import React from 'react'; import { DropTarget } from 'react-dnd'; import InprogressListsItem from './inprogress_list_item'; const listTarget = { drop(props, monitor) { const list = monitor.getItem(); props.onMoveList({ list: list.list, destination: 'inprogressLists' }); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } const InprogressLists = (props) => { const listItems = props.lists.map((list) => { return ( <InprogressListsItem key={list.id} list={list}/> ); }); const { isOver, canDrop, connectDropTarget } = props; return connectDropTarget( <ul className="col-md-12 list-group column-small"> <li className="column-title">In progress lists</li> { listItems } </ul> ); } export default DropTarget('list', listTarget, collect)(InprogressLists);
src/index.js
sblesson/resume
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/components/Navbar/Navbar.js
bryanlelliott/bryan_site_react
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import './Navbar.less'; import React from 'react'; // eslint-disable-line no-unused-vars class Navbar { render() { return ( <div className="navbar-top" role="navigation"> <a className="navbar-brand row" href="/"> <span><b>BRYAN</b>SITE</span> </a> </div> ); } } export default Navbar;
indico/web/client/js/jquery/widgets/jinja/duration_widget.js
indico/indico
// This file is part of Indico. // Copyright (C) 2002 - 2022 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import React from 'react'; import ReactDOM from 'react-dom'; import {WTFDurationField} from 'indico/react/components'; window.setupDurationWidget = function setupDurationWidget({fieldId, required, disabled}) { // Make sure the results dropdown is displayed above the dialog. const field = $(`#${fieldId}`); field.closest('.ui-dialog-content').css('overflow', 'inherit'); field.closest('.exclusivePopup').css('overflow', 'inherit'); ReactDOM.render( <WTFDurationField timeId={`${fieldId}-timestorage`} required={required} disabled={disabled} />, document.getElementById(fieldId) ); };
js/components/sideBar/index.js
amandamfielding/Coffee-Shop-Mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Image, View } from 'react-native'; import { Content, Text, List, ListItem, ProgressBar } from 'native-base'; import { firebaseApp } from "../auth/authentication"; import { Font } from 'exponent'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import { actions } from 'react-native-navigation-redux-helpers'; import { setIndex } from '../../actions/list'; import { closeDrawer } from '../../actions/drawer'; import navigateTo from '../../actions/sideBarNav'; import myTheme from '../../themes/base-theme'; import Exponent from 'exponent'; import styles from './styles'; const { reset, pushRoute, } = actions; class SideBar extends Component { static propTypes = { // setIndex: React.PropTypes.func, navigateTo: React.PropTypes.func, } constructor(props) { super(props); this.state = { fontLoaded: false, progress: 30 }; } navigateTo(route) { this.props.navigateTo(route, 'home'); } goToNews() { this.props.pushRoute({ key: 'news', index: 1 }, this.props.navigation.key); this.props.closeDrawer(); } goToLocations() { this.props.pushRoute({ key: 'locations', index: 1 }, this.props.navigation.key); this.props.closeDrawer(); } signOut() { firebaseApp.auth().signOut() .then(() => { this.props.reset(this.props.navigation.key) }, (error) => { console.log(error) }) this.props.closeDrawer(); } async componentDidMount() { await Font.loadAsync({ 'veneer': require('../../../assets/fonts/veneer.ttf'), }); this.setState({ fontLoaded: true }); } render() { if (!this.state.fontLoaded) {return null;} const news = this.state.fontLoaded ? "What's new?" : null; const locations = this.state.fontLoaded ? "Find A Store" : null; const signout = this.state.fontLoaded ? "Sign Out" : null; let pic; let name = ""; if (firebaseApp.auth().currentUser != null && this.props.user.picture != null) { pic = this.props.user.picture.data.url name = firebaseApp.auth().currentUser.displayName } let profilePic = (pic != null) ? (<Image style={styles.profilePic} source={{uri: this.props.user.picture.data.url}}/>) : (<Image style={styles.profilePic} source={require('../../../images/profilePicDefault.png')}/>) return ( <Content style={styles.sidebar} > <View style={styles.profile}> {profilePic} <Text style={{color:"white", alignSelf: "center", fontFamily: "veneer", fontSize: 24, paddingTop: 12 }}>{name}</Text> </View> <List style={styles.list}> <ListItem style={styles.listItem} button onPress={this.goToNews.bind(this)} > <Text style={styles.itemText} >{news}</Text> </ListItem> <ListItem style={styles.listItem} button onPress={this.goToLocations.bind(this)} > <Text style={styles.itemText}>{locations}</Text> </ListItem> <ListItem style={styles.listItem} button onPress={() => this.signOut()} > <Text style={styles.itemText}>{signout}</Text> </ListItem> </List> </Content> ); } } function bindAction(dispatch) { return { setIndex: index => dispatch(setIndex(index)), navigateTo: (route, homeRoute) => dispatch(navigateTo(route, homeRoute)), reset: key => dispatch(reset([{ key: 'logIn' }], key, 0)), closeDrawer: () => dispatch(closeDrawer()), pushRoute: (route, key) => dispatch(pushRoute(route, key)) }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, user: state.user.user }); export default connect(mapStateToProps, bindAction)(SideBar);
examples/dynamic-segments/app.js
fiture/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
src/components/Nav.js
jeremyburr/psyburr
import React from 'react' import Radium from 'radium' import NavLink from '../containers/NavLink.js' const rowStyle = { textAlign: 'center', '@media (min-width: 320px)' : { marginTop: '30px' }, '@media (min-width: 375px)' : { marginTop: '40px' }, '@media (min-width: 414px)' : { marginTop: '50px' }, '@media (min-width: 768px)' : { marginTop: '75px' }, } const middleLink = { display: 'inline', '@media (min-width: 320px)' : { //border: 'solid 1px red', width: '80px', paddingLeft: '25px', paddingRight: '25px', }, '@media (min-width: 375px)' : { width: '81px', paddingLeft: '30px', paddingRight: '31px', }, '@media (min-width: 414px)' : { width: '80px', paddingLeft: '35px', paddingRight: '35px', }, '@media (min-width: 768px)' : { width: '80px', paddingLeft: '115px', paddingRight: '115px', } } let Nav = () => ( <div style={rowStyle}> <NavLink target='1'> About </NavLink> <NavLink target='2'> <div style={middleLink}> Endeavors </div> </NavLink> <NavLink target='3'> Contact </NavLink> </div> ) Nav = Radium(Nav) export default Nav
docs/app/Examples/elements/Header/Content/HeaderExampleSubheaderProp.js
aabustamante/Semantic-UI-React
import React from 'react' import { Header } from 'semantic-ui-react' const HeaderExampleSubheaderProp = () => ( <Header as='h2' content='Account Settings' subheader='Manage your account settings and set email preferences' /> ) export default HeaderExampleSubheaderProp
js/src/components/Scene/SceneControls.js
scottdonaldson/voxcel
import React from 'react'; import CONFIG from '../../config'; import swal from 'sweetalert'; class SceneControls extends React.Component { constructor() { super(); } takeSnapshot() { let canvas = $(this.props.controlManager.canvas); canvas.addClass('faded'); $.ajax({ url: CONFIG.imgurEndpoint, type: 'POST', headers: { Authorization: 'Client-ID ' + CONFIG.imgurId, Accept: 'application/json' }, data: { image: canvas[0].toDataURL().split(',')[1], type: 'base64' }, success(result) { let id = result.data.id; console.log('success', CONFIG.imgurPrefix + '/' + id); }, error(err) { console.log('error uploading', err); } }); setTimeout(() => { canvas.removeClass('faded'); }, 350); } changeColor() { this.props.controlManager.changeColor(this.refs.colorPicker.value); } render() { return this.props.isAdmin ? ( <div id="scene-controls"> <input type="color" id="color-picker" ref="colorPicker" onChange={this.changeColor.bind(this)} /> <img src="/img/icons/camera.svg" onClick={this.takeSnapshot.bind(this)} /> </div> ) : null; } } export default SceneControls;
app/app.js
projectcashmere/admin
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import FontFaceObserver from 'fontfaceobserver'; import 'react-select/dist/react-select.css'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then( () => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); } ); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = messages => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { new Promise(resolve => { resolve(import('intl')); }) .then(() => Promise.all([import('intl/locale-data/jsonp/en.js')])) .then(() => render(translationMessages)) .catch(err => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
node_modules/react-bootstrap/es/MediaListItem.js
mohammed52/something.pk
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaListItem = function (_React$Component) { _inherits(MediaListItem, _React$Component); function MediaListItem() { _classCallCheck(this, MediaListItem); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaListItem.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('li', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaListItem; }(React.Component); export default bsClass('media', MediaListItem);
docs/app/Examples/views/Card/index.js
aabustamante/Semantic-UI-React
import React from 'react' import Content from './Content' import Types from './Types' import Variations from './Variations' const CardExamples = () => ( <div> <Types /> <Content /> <Variations /> </div> ) export default CardExamples
packages/xo-web/src/xo-app/settings/cloud-configs/index.js
vatesfr/xo-web
import _ from 'intl' import ActionButton from 'action-button' import decorate from 'apply-decorators' import defined from '@xen-orchestra/defined' import React from 'react' import SortedTable from 'sorted-table' import { addSubscriptions } from 'utils' import { AvailableTemplateVars, DEFAULT_CLOUD_CONFIG_TEMPLATE } from 'cloud-config' import { Container, Col } from 'grid' import { find } from 'lodash' import { generateId } from 'reaclette-utils' import { injectState, provideState } from 'reaclette' import { Text } from 'editable' import { Textarea as DebounceTextarea } from 'debounce-input-decorator' import { createCloudConfig, deleteCloudConfigs, editCloudConfig, subscribeCloudConfigs } from 'xo' // =================================================================== const COLUMNS = [ { itemRenderer: _ => _.id.slice(4, 8), name: _('formId'), sortCriteria: _ => _.id.slice(4, 8), }, { itemRenderer: ({ id, name }) => <Text value={name} onChange={name => editCloudConfig(id, { name })} />, sortCriteria: 'name', name: _('formName'), default: true, }, ] const ACTIONS = [ { handler: deleteCloudConfigs, icon: 'delete', individualLabel: _('deleteCloudConfig'), label: _('deleteSelectedCloudConfigs'), level: 'danger', }, ] const INDIVIDUAL_ACTIONS = [ { handler: (cloudConfig, { populateForm }) => populateForm(cloudConfig), icon: 'edit', label: _('editCloudConfig'), level: 'primary', }, ] const initialParams = { cloudConfigToEditId: undefined, name: '', template: undefined, } export default decorate([ addSubscriptions({ cloudConfigs: subscribeCloudConfigs, }), provideState({ initialState: () => initialParams, effects: { setInputValue: (_, { target: { name, value } }) => state => ({ ...state, [name]: value, }), reset: () => state => ({ ...state, ...initialParams, }), createCloudConfig: ({ reset }) => async ({ name, template = DEFAULT_CLOUD_CONFIG_TEMPLATE }) => { await createCloudConfig({ name, template }) reset() }, editCloudConfig: ({ reset }) => async ({ name, template, cloudConfigToEditId }, { cloudConfigs }) => { const oldCloudConfig = find(cloudConfigs, { id: cloudConfigToEditId }) if (oldCloudConfig.name !== name || oldCloudConfig.template !== template) { await editCloudConfig(cloudConfigToEditId, { name, template }) } reset() }, populateForm: (_, { id, name, template }) => state => ({ ...state, name, cloudConfigToEditId: id, template, }), }, computed: { formId: generateId, inputNameId: generateId, inputTemplateId: generateId, isInvalid: ({ name, template }) => name.trim() === '' || (template !== undefined && template.trim() === ''), }, }), injectState, ({ state, effects, cloudConfigs }) => ( <Container> <Col mediumSize={6}> <form id={state.formId}> <div className='form-group'> <label htmlFor={state.inputNameId}> <strong>{_('formName')}</strong>{' '} </label> <input className='form-control' id={state.inputNameId} name='name' onChange={effects.setInputValue} type='text' value={state.name} /> </div>{' '} <div className='form-group'> <label htmlFor={state.inputTemplateId}> <strong>{_('settingsCloudConfigTemplate')}</strong>{' '} </label>{' '} <AvailableTemplateVars /> <DebounceTextarea className='form-control' id={state.inputTemplateId} name='template' onChange={effects.setInputValue} rows={12} value={defined(state.template, DEFAULT_CLOUD_CONFIG_TEMPLATE)} /> </div>{' '} {state.cloudConfigToEditId !== undefined ? ( <ActionButton btnStyle='primary' disabled={state.isInvalid} form={state.formId} handler={effects.editCloudConfig} icon='edit' > {_('formEdit')} </ActionButton> ) : ( <ActionButton btnStyle='success' disabled={state.isInvalid} form={state.formId} handler={effects.createCloudConfig} icon='add' > {_('formCreate')} </ActionButton> )} <ActionButton className='pull-right' handler={effects.reset} icon='cancel'> {_('formCancel')} </ActionButton> </form> </Col> <Col mediumSize={6}> <SortedTable actions={ACTIONS} collection={cloudConfigs} columns={COLUMNS} data-populateForm={effects.populateForm} individualActions={INDIVIDUAL_ACTIONS} stateUrlParam='s' /> </Col> </Container> ), ])
src/index.js
chasm/tic-tac-routes
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router, Route } from 'react-router' import { createHistory } from 'history' import { syncReduxAndRouter } from 'redux-simple-router' import store from './store' import HomeView from './views/home' import GamesView from './views/games' const history = createHistory() syncReduxAndRouter(history, store) const render = () => { ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/" component={HomeView}> <Route path="/games/:id" component={GamesView}/> </Route> </Router> </Provider>, document.getElementById('app') ) } store.subscribe(render) render()
src/stories/mobile/cityInfo.js
Cirych/WeatherApp
import React from 'react'; import { storiesOf, addDecorator, action, linkTo } from '@kadira/storybook'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MobileTearSheet from './MobileTearSheet'; import weatherData from '../api/data'; import forecastData from '../api/forecast'; import CityInfo from '../../components/CityInfo'; const MobileDecorator = story => ( <MuiThemeProvider> <MobileTearSheet customColor="lightblue"> {story()} </MobileTearSheet> </MuiThemeProvider> ); const cityInfoData = { ...weatherData[0], forecast: forecastData.list }; storiesOf('Mobile.CityInfo', module) .addDecorator(MobileDecorator) .add('Info', () => ( <CityInfo city={cityInfoData} /> ))
src/components/callout/index.js
adrienlozano/stephaniewebsite
import React from 'react'; import Section from '~/components/section'; import styled from 'styled-components'; import Typography from '~/components/typography'; import PageSection from "~/components/page-section"; import CalloutButton from './button'; import withSettings from "~/enhancers/with-settings"; const CalloutSection = ({className, heading, subHeading}) => { return (<PageSection className={className} bg="dark" py={128} > <Typography component="h1" color="#FFF" f={[4, 6]}>{heading}</Typography> <Typography component="h2" color="#FFF" f={[2, 4]}>{subHeading}</Typography> <CalloutButton color="white" href="contact">Contact Us</CalloutButton> </PageSection>) }; const withCalloutSettings = withSettings( settings => ({ ...settings.map(x => x.landing).map(x => x.callout).getOrElse({}) }) ); export default withCalloutSettings(styled(CalloutSection)` text-align:center; `);
test/components/WorldMap-test.js
davrodpin/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import {test} from 'tape'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import WorldMap from '../../src/js/components/WorldMap'; import CSSClassnames from '../../src/js/utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.WORLD_MAP; test('loads a WorldMap', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(WorldMap, { series: [{continent: 'Australia'}] })); const worldMapElement = shallowRenderer.getRenderOutput(); if (worldMapElement.props.className.indexOf(CLASS_ROOT) > -1) { t.pass('WorldMap has class'); } else { t.fail('WorldMap does not have class'); } });
packages/react-events/src/Drag.js
STRML/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ReactResponderEvent, ReactResponderContext, } from 'shared/ReactTypes'; import React from 'react'; const targetEventTypes = ['pointerdown']; const rootEventTypes = [ 'pointerup', 'pointercancel', {name: 'pointermove', passive: false}, ]; type DragState = { dragTarget: null | Element | Document, isPointerDown: boolean, isDragging: boolean, startX: number, startY: number, x: number, y: number, }; // In the case we don't have PointerEvents (Safari), we listen to touch events // too if (typeof window !== 'undefined' && window.PointerEvent === undefined) { targetEventTypes.push('touchstart', 'mousedown'); rootEventTypes.push('mouseup', 'mousemove', 'touchend', 'touchcancel', { name: 'touchmove', passive: false, }); } type EventData = { diffX: number, diffY: number, }; type DragEventType = 'dragstart' | 'dragend' | 'dragchange' | 'dragmove'; type DragEvent = {| target: Element | Document, type: DragEventType, timeStamp: number, diffX?: number, diffY?: number, |}; function createDragEvent( context: ReactResponderContext, type: DragEventType, target: Element | Document, eventData?: EventData, ): DragEvent { return { target, type, timeStamp: context.getTimeStamp(), ...eventData, }; } function dispatchDragEvent( context: ReactResponderContext, name: DragEventType, listener: DragEvent => void, state: DragState, discrete: boolean, eventData?: EventData, ): void { const target = ((state.dragTarget: any): Element | Document); const syntheticEvent = createDragEvent(context, name, target, eventData); context.dispatchEvent(syntheticEvent, listener, {discrete}); } const DragResponder = { targetEventTypes, createInitialState(): DragState { return { dragTarget: null, isPointerDown: false, isDragging: false, startX: 0, startY: 0, x: 0, y: 0, }; }, stopLocalPropagation: true, onEvent( event: ReactResponderEvent, context: ReactResponderContext, props: Object, state: DragState, ): void { const {target, type, nativeEvent} = event; switch (type) { case 'touchstart': case 'mousedown': case 'pointerdown': { if (!state.isDragging) { if (props.onShouldClaimOwnership) { context.releaseOwnership(); } const obj = type === 'touchstart' ? (nativeEvent: any).changedTouches[0] : nativeEvent; const x = (state.startX = (obj: any).screenX); const y = (state.startY = (obj: any).screenY); state.x = x; state.y = y; state.dragTarget = target; state.isPointerDown = true; if (props.onDragStart) { dispatchDragEvent( context, 'dragstart', props.onDragStart, state, true, ); } context.addRootEventTypes(rootEventTypes); } break; } } }, onRootEvent( event: ReactResponderEvent, context: ReactResponderContext, props: Object, state: DragState, ): void { const {type, nativeEvent} = event; switch (type) { case 'touchmove': case 'mousemove': case 'pointermove': { if (event.passive) { return; } if (state.isPointerDown) { const obj = type === 'touchmove' ? (nativeEvent: any).changedTouches[0] : nativeEvent; const x = (obj: any).screenX; const y = (obj: any).screenY; state.x = x; state.y = y; if (!state.isDragging && x !== state.startX && y !== state.startY) { let shouldEnableDragging = true; if ( props.onShouldClaimOwnership && props.onShouldClaimOwnership() ) { shouldEnableDragging = context.requestGlobalOwnership(); } if (shouldEnableDragging) { state.isDragging = true; if (props.onDragChange) { const dragChangeEventListener = () => { props.onDragChange(true); }; dispatchDragEvent( context, 'dragchange', dragChangeEventListener, state, true, ); } } else { state.dragTarget = null; state.isPointerDown = false; context.removeRootEventTypes(rootEventTypes); } } else { if (props.onDragMove) { const eventData = { diffX: x - state.startX, diffY: y - state.startY, }; dispatchDragEvent( context, 'dragmove', props.onDragMove, state, false, eventData, ); } (nativeEvent: any).preventDefault(); } } break; } case 'pointercancel': case 'touchcancel': case 'touchend': case 'mouseup': case 'pointerup': { if (state.isDragging) { if (props.onShouldClaimOwnership) { context.releaseOwnership(); } if (props.onDragEnd) { dispatchDragEvent(context, 'dragend', props.onDragEnd, state, true); } if (props.onDragChange) { const dragChangeEventListener = () => { props.onDragChange(false); }; dispatchDragEvent( context, 'dragchange', dragChangeEventListener, state, true, ); } state.isDragging = false; } if (state.isPointerDown) { state.dragTarget = null; state.isPointerDown = false; context.removeRootEventTypes(rootEventTypes); } break; } } }, }; export default React.unstable_createEventComponent(DragResponder, 'Drag');
src/components/Html.js
Maryanushka/masterskaya
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright ยฉ 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; import config from '../config'; /* eslint-disable react/no-danger */ class Html extends React.Component { static propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, styles: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, cssText: PropTypes.string.isRequired, }).isRequired), scripts: PropTypes.arrayOf(PropTypes.string.isRequired), app: PropTypes.object, // eslint-disable-line children: PropTypes.string.isRequired, }; static defaultProps = { styles: [], scripts: [], }; render() { const { title, description, styles, scripts, app, children } = this.props; return ( <html className="no-js" lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" /> {styles.map(style => ( <style key={style.id} id={style.id} dangerouslySetInnerHTML={{ __html: style.cssText }} /> ))} </head> <body> <div id="app" dangerouslySetInnerHTML={{ __html: children }} /> <script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} /> {scripts.map(script => <script key={script} src={script} />)} <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </body> </html> ); } } export default Html;
demo/containers/FormV1/Fields.js
vbait/vb-react-form
import React from 'react'; import PropTypes from 'prop-types'; import { Button, FormGroup, ControlLabel, FormControl, HelpBlock, Alert } from 'react-bootstrap'; import { VBForm, connectForm } from '../../../src/Forms'; const Actions = ({ form }) => { const isValid = form.isValid(); return ( <Button type="submit" bsStyle="success" disabled={!isValid}> {isValid ? 'Submit' : 'Not Valid'} </Button> ) }; Actions.propTypes = { form: PropTypes.object.isRequired, }; const FormActions = connectForm(Actions); class FormFieldWrapper extends React.Component { state = { invalid: false, }; onFieldChange = (model) => { this.setState(() => ({ invalid: model.touched && !model.isValid(), errors: model.errors(), })); }; render() { const { id, label } = this.props; const { invalid, errors } = this.state; return ( <FormGroup controlId={id} validationState={invalid ? 'error' : null}> {label && <ControlLabel>{label}</ControlLabel>} <VBForm.Field {...this.props} onFieldChange={this.onFieldChange} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ) } } const PasswordField = ({ model, ...props }) => { const invalid = model.touched && !model.isValid(); const errors = model.errors(); return ( <FormGroup controlId={props.id} validationState={invalid ? 'error' : null}> {props.label && <ControlLabel>{props.label}</ControlLabel>} <InputField {...props} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ); }; const RBField = ({ model, ...props }) => { const invalid = model.touched && !model.isValid(); const errors = model.errors(); return ( <FormGroup controlId={props.id} validationState={invalid ? 'error' : null}> {props.label && <ControlLabel>{props.label}</ControlLabel>} <InputField {...props} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ); }; class InputField extends React.PureComponent { onChange = (event) => { event.preventDefault(); this.props.onChange(event.target.value); }; render() { const { value, ...other } = this.props; return ( <FormControl value={value || ''} {...other} onChange={this.onChange} /> ) } } const ErrorComponent = ({ form, field }) => { let errors = []; let invalid = false; if (field) { errors = field.errors(); invalid = field.touched && !field.isValid(); } else { errors = form.errors().form; invalid = form.isTouched() && errors.length; } return ( <div> {invalid ? ( <Alert bsStyle="danger"> {errors.map(error => ( <div key={error}>{error}</div> ))} </Alert> ) : null} </div> ) }; export { FormActions, FormFieldWrapper, PasswordField, InputField, ErrorComponent, RBField, };
src/svg-icons/av/forward-10.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward10 = (props) => ( <SvgIcon {...props}> <path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvForward10 = pure(AvForward10); AvForward10.displayName = 'AvForward10'; AvForward10.muiName = 'SvgIcon'; export default AvForward10;
node_modules/react-router/es6/withRouter.js
TheeSweeney/ComplexReactReduxMiddlewareReview
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; var props = _extends({}, this.props, { router: router }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-v3-slider.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import Environment from '../environment/environment.js'; import {BaseMixin, ElementaryMixin, ContentMixin, Tools} from './../common/common.js'; import {Glyphicon} from './../bricks/bricks.js'; import Slid from './../bricks/slider.js'; import InputMixin from './mixins/input-mixin.js'; import Number from './number.js'; import TextInput from './internal/text-input.js'; import './slider.less'; export const Slider = React.createClass({ mixins: [ BaseMixin, ElementaryMixin, ContentMixin, InputMixin ], statics: { tagName: 'UU5.Forms.Slider', classNames: { main: 'uu5-forms-slider', inputGroup: 'uu5-forms-slider-input-group', slider: 'uu5-forms-slider-slider', number: 'uu5-forms-slider-number' }, defaults: { nanMessage: 'Please insert a number', } }, propTypes: { colorSchema: React.PropTypes.oneOf(Environment.colorSchema), // TODO //position: React.PropTypes.oneOf(['horizontal', 'vertical']), min: React.PropTypes.number, max: React.PropTypes.number, step: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func, onChanged: React.PropTypes.func }, // Setting defaults getDefaultProps() { return { colorSchema: 'default', //position: 'horizontal', min: 0, max: 10, step: 1, value: null, onChanged: null }; }, componentWillMount(){ let value = typeof this.props.value === 'number' ? this.props.value : this.props.min; if (this.props.onValidate && typeof this.props.onValidate === 'function') { this._validateOnChange({value: value, event: null, component: this}) } else { this.setInitial(null, value) } return this; }, componentWillReceiveProps(nextProps) { if (this.props.controlled) { let value = typeof this.props.value === 'number' ? nextProps.value : nextProps.min; this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value) } return this; }, // Interface // Overriding Functions setValue_(value, setStateCallback) { if (typeof this.props.onValidate === 'function') { this._validateOnChange({value:value}) } else { this.props.required ? this.setSuccess(null, value, setStateCallback) : this.setInitial(null, value, setStateCallback); } return this; }, // Component Specific Helpers // _onChange(e) { // if (!this.isDisabled()) { // var value = !this.getValue(); // var newState = this._validateValue(value); // // if (newState) { // this.setState(newState); // } else { // if (this.props.onChange) { // this.props.onChange({ value: value, input: this, event: e }); // } else { // this.setState({ value: value }); // } // } // } // return this; // }, _validateOnChange(opt){ let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null; if (result) { if (typeof result === 'object') { if (result.feedback) { this.setFeedback(result.feedback, result.message, result.value); } else { this.setState({value: opt.value}); } } else { this.showError('validateError', null, {context: {event: e, func: this.props.onValidate, result: result}}); } } return this; }, _getMainAttrs() { return this.getInputMainAttrs(); }, _getInputGroupAttrs() { return { className: this.getClassName().inputGroup }; }, _getSliderProps() { let value = this.props.min; if (this.state.value) { value = typeof this.state.value === 'number' ? this.state.value : parseInt(this.state.value); } return { name: this.getName(), className: this.getClassName().slider, colorSchema: this.props.colorSchema, //position: 'horizontal', min: this.props.min, max: this.props.max, step: this.props.step, value: value, content: this.getContent(), onChange: this._onChange, onChanged: this.props.onChanged, disabled: this.isDisabled() || this.isReadOnly() }; }, _getNumberProps() { let value = this.state.value || 0; value = value > this.props.max ? this.props.max : (value < this.props.min) ? this.props.min : value; return { className: this.getClassName().number, min: this.props.min, max: this.props.max, value: value.toString(), onChange: (event)=> { this._onChange({component: this, value: event.target.value, event: event}) }, onBlur: (opt) => { if (this.state.value < this.props.min) { opt.component.setValue(this.props.min); } else if (this.state.value > this.props.max) { opt.component.setValue(this.props.max); } }, disabled: this.isDisabled(), onChangeFeedback: this._onChangeNumberFeedback }; }, _getOnChanged(value, e) { let onChanged; if (typeof this.props.onChanged === 'function') { onChanged = () => { this.props.onChanged({value: value, component: this, event: e}); }; } return onChanged; }, _onChange(opt) { if (!this.isDisabled()) { if (typeof this.props.onChange == 'function') { opt.component = this; this.props.onChange(opt); } else if (typeof this.props.onValidate === 'function') { this._validateOnChange(opt) } else { let result = this._checkNumberResultChange(opt); if (result.feedback && result.feedback === 'warning') { this.setFeedback(result.feedback, result.message, result.value); } else { this.setInitial(null, opt.value, this._getOnChanged(opt.value, opt.event)); } } } return this; }, _checkNumberResultChange(opt){ if (opt.value) { opt.value = opt.value.toString(); let isComma = opt.value.indexOf(',') > 0; opt.value = opt.value.trim().replace(new RegExp(this.props.thousandSeparator, 'g'), ''); opt.value = opt.value.replace(',', '.'); let isNan = isNaN(opt.value); if (isNan && opt.value != '-') { opt.value = this.state.value; opt.feedback = 'warning'; opt.message = this.getDefault().nanMessage; } isComma && (opt.value = opt.value.replace('.', ',')); } return opt; }, _onChangeNumberFeedback(opt) { this.setValue(opt.value ? +opt.value : null, opt.callback); //this.setFeedback(opt.feedback, opt.message, opt.value ? +opt.value : null, opt.callback); return this; }, _getFeedbackIcon(){ let icon = this.props.required ? this.props.successGlyphicon : null; switch (this.getFeedback()) { case 'success': icon = this.props.successGlyphicon; break; case 'warning': icon = this.props.warningGlyphicon; break; case 'error': icon = this.props.errorGlyphicon; break; } return icon; }, // Render render() { let inputId = this.getId() + '-input'; return ( <div {...this._getInputAttrs()}> {this.getLabel(inputId)} {this.getInputWrapper([ <Slid {...this._getSliderProps()}> {this.props.children && React.Children.toArray(this.props.children)} </Slid>, <TextInput {...this._getNumberProps()} id={inputId} name={this.props.name || inputId} //value={this.state.value.toString()} placeholder={this.props.placeholder} type='text' //onChange={this.onChange} //onBlur={this.onBlur} //onFocus={this.onFocus} mainAttrs={this.props.inputAttrs} disabled={this.isDisabled() || this.isLoading()} readonly={this.isReadOnly()} glyphicon={this._getFeedbackIcon()} loading={this.isLoading()} />])} </div> ); } }); export default Slider;
frontend/src/components/eois/details/overview/projectDetails.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import { browserHistory as history } from 'react-router'; import SectorForm from '../../../forms/fields/projectFields/sectorField/sectorFieldArray'; import GridColumn from '../../../common/grid/gridColumn'; import GridRow from '../../../common/grid/gridRow'; import HeaderList from '../../../common/list/headerList'; import TextField from '../../../forms/textFieldForm'; import ProjectPartners from '../../../forms/fields/projectFields/partnersField/ProjectPartners'; import PaddedContent from '../../../common/paddedContent'; import PartnersForm from '../../../forms/fields/projectFields/partnersField/partnersFieldArray'; import { Attachments, TitleField, FocalPoint, OtherInfo, Background, Goal, StartDate, EndDate, DeadlineDate, ClarificationRequestDeadlineDate, NotifyDate, } from '../../../forms/fields/projectFields/commonFields'; import LocationFieldReadOnlyArray from '../../../forms/fields/projectFields/locationField/locationFieldReadOnlyArray'; import SpreadContent from '../../../common/spreadContent'; import { PROJECT_TYPES, ROLES } from '../../../../helpers/constants'; import OrganizationTypes from '../../../forms/fields/projectFields/organizationType'; import Agencies from '../../../forms/fields/projectFields/agencies'; const messages = { title: 'Project Details', labels: { id: 'CFEI ID:', dsrId: 'DSR ID:', issued: 'Issued by', goal: 'Expected Results', agency: 'Agency', partner: 'Organization\'s Legal Name', type: 'Type of Organization', viewProfile: 'view partner\'s profile', }, }; const Fields = ({ type, role, partnerId, displayGoal, formName }) => { if (type === PROJECT_TYPES.UNSOLICITED) { return (<PaddedContent> <GridColumn > {role === ROLES.AGENCY && <GridRow columns={2} > <ProjectPartners fieldName="partner_name" label={messages.labels.partner} readOnly /> <OrganizationTypes fieldName="display_type" label={messages.labels.type} readOnly /> </GridRow>} <TitleField readOnly /> {role === ROLES.PARTNER && <Agencies fieldName="agency" readOnly />} <LocationFieldReadOnlyArray formName={formName} /> <SectorForm readOnly /> {role === ROLES.AGENCY && <Grid container justify="flex-end"> <Grid item> <Button onClick={() => history.push(`/partner/${partnerId}/details`)} color="accent" > {messages.labels.viewProfile} </Button> </Grid> </Grid>} </GridColumn> </PaddedContent>); } return (<PaddedContent> <GridColumn > <TitleField readOnly /> {role === ROLES.AGENCY ? <FocalPoint readOnly /> : null} <LocationFieldReadOnlyArray formName={formName} /> <SectorForm readOnly /> <Agencies fieldName="agency" label={messages.labels.issued} readOnly /> <Background readOnly /> {displayGoal && <Goal readOnly />} <OtherInfo readOnly /> {type === PROJECT_TYPES.OPEN && <GridRow columns={3} > <ClarificationRequestDeadlineDate readOnly /> <DeadlineDate readOnly /> <NotifyDate readOnly /> </GridRow>} <GridRow columns={2} > <StartDate readOnly /> <EndDate readOnly /> </GridRow> {type === PROJECT_TYPES.OPEN && <Attachments readOnly />} {type === PROJECT_TYPES.DIRECT && <PartnersForm hidePartner readOnly />} </GridColumn> </PaddedContent>); }; Fields.propTypes = { type: PropTypes.string, role: PropTypes.string, partner: PropTypes.string, formName: PropTypes.string, partnerId: PropTypes.number, displayGoal: PropTypes.bool, }; const title = type => () => ( <SpreadContent> <Typography type="headline" >{messages.title}</Typography> {type !== PROJECT_TYPES.UNSOLICITED && <TextField fieldName="displayID" label={(type === PROJECT_TYPES.OPEN || type === PROJECT_TYPES.PINNED) ? messages.labels.id : messages.labels.dsrId} readOnly />} </SpreadContent> ); const ProjectDetails = ({ type, role, partner, partnerId, displayGoal, formName }) => ( <HeaderList header={title(type)} > <Fields formName={formName} type={type} role={role} partner={partner} partnerId={partnerId} displayGoal={displayGoal} /> </HeaderList> ); ProjectDetails.propTypes = { type: PropTypes.string, role: PropTypes.string, partner: PropTypes.string, partnerId: PropTypes.number, displayGoal: PropTypes.bool, }; export default ProjectDetails;
web/src/components/preview.js
ajmalafif/ajmalafif.com
import React from 'react' import tw, { css } from 'twin.macro' export const Preview = React.forwardRef(function Preview(props, ref) { return ( <div {...props} tw="block relative bg-gradient-to-t" css={{ height: 'max(40rem, 30vmin)', marginTop: '-40rem', '--tw-gradient-from': 'var(--bg-primary)', '--tw-gradient-stops': 'var(--tw-gradient-from), var(--tw-gradient-to, rgba(255, 255, 255, 0))', gridColumn: '1 / 4' }} > {ref} </div> ) })
test/index.js
zhbhun/react-window-kit
/** * Created by zhbhun on 2015/9/17. */ import React from 'react'; import {Window, Modal, Confirm, Tip} from './bootstrap'; import assign from 'object-assign'; // modal demo class ModalDemo extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open modal</button> <Modal visible={this.state.show} size='lg' header='Title' onHide={this.closeWindow.bind(this)} onCancel={this.closeWindow.bind(this)} onConfirm={this.closeWindow.bind(this)} > <h3>Hello Modal!</h3> </Modal> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ModalDemo/>, document.getElementById('modal-demo')); // --- // confirm demo class ConfirmDemo extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open confirm</button> <Confirm visible={this.state.show} title='Are you sure!' onCancel={this.closeWindow.bind(this)} onOk={this.closeWindow.bind(this)} > Hello Modal! Hello Modal! Hello Modal! Hello Modal! Hello Modal! </Confirm> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ConfirmDemo/>, document.getElementById('confirm-demo')); // --- // tip demo class ConfirmTip extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open tip</button> <Tip visible={this.state.show} type='info' title='Are you sure!' onOk={this.closeWindow.bind(this)} > Hello Modal! Hello Modal! Hello Modal! Hello Modal! Hello Modal! </Tip> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ConfirmTip/>, document.getElementById('tip-demo'));
service-worker-prototype/src/index.js
ericapisani/service-worker-prototype
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
public/containers/CourseList/UserPaymentBlock.js
ninjiangstar/hackSChedule
import React, { Component } from 'react'; import classnames from 'classnames'; import api from '../../utils/api-interface'; import StripeCheckout from 'react-stripe-checkout'; class UserPaymentBlock extends Component { constructor(props) { super(props); this.state = { errorMessage: '', paymentInProgress: false, paid: false }; if (window.location.hostname == 'hackschedule.com') { this.stripeKey = 'pk_live_qmovCOmw8NHmyjlH9PPu3Jgp'; } else { this.stripeKey = 'pk_test_VJUKGjbH9Amo8DwJhqDeCAtM'; } this.socket = io(); this.onToken = this.onToken.bind(this); this.close = this.close.bind(this); this.userChangedPaid = this.userChangedPaid.bind(this); } componentWillMount() { this.socket.on('receive:userChangedPaid', this.userChangedPaid); } componentWillUnmount() { this.socket.off('receive:userChangedPaid', this.userChangedPaid); } userChangedPaid({ email: userChangedEmail, paid }) { const { email } = this.props; if (email == userChangedEmail && paid) this.setState({ paid }); } renderPayment() { const { email } = this.props; const { errorMessage, paymentInProgress } = this.state; return <div className='start upgrade'> <h3 className='red'>Upgrade Features for $2 ๐Ÿ™</h3> <div> <p>Hosting and maintaining this service is expensive! I need your help to offset the costs of building and running this app. For $2, you get to unlock the ability to <b>see more than 25 options, pin class sections, and block out unavailabilities</b>!</p> </div> <div> <StripeCheckout token={this.onToken} stripeKey={this.stripeKey} name="HackSChedule Upgrade" description="by Andrew Jiang" amount={200} currency="USD" allowRememberMe={false} email={email}> <button className="red">Pay With Card</button> </StripeCheckout> <button className="blue" onClick={() => { window.open('https://venmo.com/?txn=pay&audience=friends&recipients=ninjiangstar&amount=2&note=hackschedule_id:' + email.split('@')[0]) }}>Venmo</button> </div> {(() => { if (errorMessage.length > 0) return <div className='alert'>{errorMessage}</div>; })()} </div>; } renderThankYou() { return <div className='start upgrade'> <p><b>Thank you and good luck!</b></p> <button onClick={this.close}>Activate Upgrades Now</button> </div>; } render() { const { paid } = this.state; const { paid: isUserPaid } = this.props; if (isUserPaid) return null; else if(!paid) return this.renderPayment(); else return this.renderThankYou(); } onToken(token) { let { email, pin } = this.props; this.setState({ paymentInProgress: true, errorMessage: '' }); api.post(api.user.pay(email), { pin, token }) .then(response => { if (response.paid) { this.setState({ paid: true }); } else { this.setState({ paymentInProgress: false, paid: false, errorMessage: 'Unable to process payment: ' + response.error }); } }); } close() { this.props.close({ action: 'PAYMENT', paid: this.state.paid }); } } export default UserPaymentBlock;
auth/src/components/common/CardSection.js
DaveWJ/LearningReact
/** * Created by david on 2/22/17. */ import React from 'react'; import { View } from 'react-native'; const CardSection = (props) => { return ( <View style={styles.containerStyle}> {props.children} </View> ); }; const styles = { containerStyle: { borderBottomWidth: 1, padding: 5, backgroundColor: '#fff', justifyContent: 'flex-start', flexDirection: 'row', borderColor: '#ddd', position: 'relative' } }; export { CardSection };
src/components/Icons/Mute/index.js
jmikrut/keen-2017
import React from 'react'; import './Mute.css'; export default (props) => { if (props.color) { this.color = props.color; } else { this.color = '#4df7ca'; } return ( <svg className="mute" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <polyline stroke={this.color} points="8.47 14.91 11.07 17.74 11.07 11.08"/> <path stroke={this.color} d="M11.07,6.48V2.26L5.6,7.71H3.17A1.26,1.26,0,0,0,2,8.92v2.43a1.19,1.19,0,0,0,1.13,1.22H5"/> <path stroke={this.color} d="M13.45,9.93a1.91,1.91,0,0,1-1.92,1.91h-.46"/> <line stroke={this.color} x1="2.56" y1="17.74" x2="18.05" y2="2.26"/> </svg> ); }
app/containers/CreateBundle.js
kaunio/gloso
// @flow import React, { Component } from 'react'; import { withRouter } from 'react-router' import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import LanguagePair from '../components/LanguagePair'; import * as glosorActions from '../actions/glosorActions'; class HomePage extends Component { createFn(lang1, lang2) { this.props.setLangs(lang1, lang2); this.props.router.push("/addGlosor"); } render() { return ( <LanguagePair createFn={(a,b) => this.createFn(a,b)} /> ); } } function mapStateToProps(state) { return { }; } function mapDispatchToProps(dispatch) { return bindActionCreators(glosorActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(withRouter(HomePage));
src/components/Feedback/Feedback.js
hang-up/react-whatever
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
examples/huge-apps/routes/Grades/components/Grades.js
ArmendGashi/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
app/containers/App.js
pavelkomiagin/npmr
// @flow import React, { Component } from 'react'; export default class App extends Component { props: { children: HTMLElement }; render() { return ( <div> {this.props.children} </div> ); } }
src/Register.js
RobertMcCoy/CodeCollaborator
import React, { Component } from 'react'; import './Register.css'; import './main.css'; import { Redirect } from 'react-router'; import axios from 'axios'; import validator from 'validator'; class Register extends Component { constructor(props) { super(props); this.state = { errors: {}, user: { email: '', firstname: '', lastname: '', username: '', password: '', confirmPassword: '' }, registered: false } this.verifyInput = this.verifyInput.bind(this); this.handleForm = this.handleForm.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { event.preventDefault(); for (var property in this.state.user) { this.verifyInput(property, this.state.user[property]); } for (var error in this.state.errors) { if (this.state.errors[error].length > 0) { return false; } } axios.post('/auth/signup', { 'username': this.state.user.username, 'email': this.state.user.email, 'password': this.state.user.password, 'firstname': this.state.user.firstname, 'lastname': this.state.user.lastname }).then((response) => { if (response.status === 200) { localStorage.setItem('jwtToken', response.data.token); } this.setState({ registered: true }) }).catch((response) => { localStorage.setItem('jwtToken', ''); this.setState({ errors: { registrationError: response.data } }) }); } verifyInput(field, value) { var currentErrors = this.state.errors; if (field === "email") { if (!validator.isEmail(value)) { currentErrors.emailError = "Email must be a valid address!"; this.setState({ errors: currentErrors }); } else { currentErrors.emailError = ""; this.setState({ errors: currentErrors }); } } if (field === "username") { if (!value) { currentErrors.userNameError = "Username must be present!"; this.setState({ errors: currentErrors }); } } if (field === "firstname") { if (!value) { currentErrors.firstNameError = "First Name must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "lastname") { if (!value) { currentErrors.lastNameError = "Last Name must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "password") { if (!value) { currentErrors.passwordError = "Password must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "password" || field === "confirmPassword") { if (this.state.user.password !== this.state.user.confirmPassword || this.state.user.password === '' || this.state.user.confirmPassword === '') { currentErrors.passwordMismatch = "Passwords must match!"; this.setState({ errors: currentErrors }); } else { currentErrors.passwordMismatch = ""; this.setState({ errors: currentErrors }); } } } handleForm(event) { const field = event.target.name; const user = this.state.user; user[field] = event.target.value; this.verifyInput(field, event.target.value); this.setState({ user }); } render() { if (this.state.registered) { return ( <Redirect to='/profile' /> ) } else { return ( <div className="container"> <form id="signup" name="signup" onSubmit={this.handleSubmit} > <h2>Sign-up for CodeCollaborator</h2> {this.state.errors.unfilledFields && <p className="code-collab-error">*{this.state.errors.unfilledFields}</p>} <div className="form-group"> <label htmlFor="email">Email*:</label> <input type="email" className="form-control" name="email" onChange={this.handleForm} value={this.state.user.email} /> {this.state.errors.emailError && <p className="code-collab-error">*{this.state.errors.emailError}</p>} </div> <div className="form-group"> <label htmlFor="firstname">First Name*:</label> <input type="text" className="form-control" name="firstname" onChange={this.handleForm} value={this.state.user.firstname} /> {this.state.errors.firstNameError && <p className="code-collab-error">*{this.state.errors.firstNameError}</p>} </div> <div className="form-group"> <label htmlFor="lastname">Last Name*:</label> <input type="text" className="form-control" name="lastname" onChange={this.handleForm} value={this.state.user.lastname} /> {this.state.errors.lastNameError && <p className="code-collab-error">*{this.state.errors.lastNameError}</p>} </div> <div className="form-group"> <label htmlFor="username">Username*:</label> <input type="text" className="form-control" name="username" onChange={this.handleForm} value={this.state.user.username} /> {this.state.errors.userNameError && <p className="code-collab-error">*{this.state.errors.userNameError}</p>} </div> <div className="form-group"> <label htmlFor="password">Password*:</label> <input type="password" className="form-control" name="password" onChange={this.handleForm} value={this.state.user.password} /> {this.state.errors.passwordError && <p className="code-collab-error">*{this.state.errors.passwordError}</p>} </div> <div className="form-group"> <label htmlFor="confirmPassword">Confirm Password*:</label> <input type="password" className="form-control" name="confirmPassword" onChange={this.handleForm} value={this.state.user.confirmPassword} /> {this.state.errors.passwordMismatch && <p className="code-collab-error">*{this.state.errors.passwordMismatch}</p>} </div> {this.state.errors.registrationError && <p className="code-collab-error">*{this.state.errors.registrationError}</p>} <input type="submit" value="Register" className="btn btn-info" /> </form> </div> ); } } } export default Register;
src/svg-icons/av/loop.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLoop = (props) => ( <SvgIcon {...props}> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/> </SvgIcon> ); AvLoop = pure(AvLoop); AvLoop.displayName = 'AvLoop'; export default AvLoop;
app/javascript/mastodon/features/ui/components/modal_loading.js
danhunsaker/mastodon
import React from 'react'; import LoadingIndicator from '../../../components/loading_indicator'; // Keep the markup in sync with <BundleModalError /> // (make sure they have the same dimensions) const ModalLoading = () => ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <LoadingIndicator /> </div> <div className='error-modal__footer'> <div> <button className='error-modal__nav onboarding-modal__skip' /> </div> </div> </div> ); export default ModalLoading;
client/src/components/ApartmentList/components/Apartment.js
uramen/apartments
import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome' import Tooltip from 'rc-tooltip'; import { Link } from 'react-router'; import 'rc-tooltip/assets/bootstrap.css'; import _ from 'lodash'; export default class Apartment extends Component { constructor(props) { super(props); this.state = { visibleType: false, visibleWifi: false, } } handleTypeHover = () => { this.setState({ visibleType: !this.state.visibleType, }); } handleWifiHover = () => { this.setState({ visibleWifi: !this.state.visibleWifi, }); } render() { return ( <div className="col-md-6 apartment"> <div className="flex-wrapp"> <div className="apartment-image"> <img src={this.props.images[0]} alt=""/> </div> <div className="apartment-info"> <h4>{_.truncate(this.props.title, {'length': 24, 'separator': ' '})}</h4> <div className="rooms-with-price"> <span className="rooms">{`${this.props.rooms}ะบ`}</span> <span className="price">{`${this.props.price} ะณั€ะฝ`}</span> </div> <div className="comfort"> <Tooltip visible={this.state.visibleType} animation="zoom" trigger={[]} overlayStyle={{ zIndex: 1000 }} overlay={<span>{this.props.type}</span>} > <div className="comfort-yellow" onClick={this.handleTypeHover.bind(this)}> { this.props.type === 'Flat' ? <FontAwesome name="building" style={{paddingLeft: 2, paddingRight: 2}} /> : <FontAwesome name="home" /> } </div> </Tooltip> <Tooltip visible={this.state.visibleWifi} animation="zoom" trigger={[]} overlayStyle={{ zIndex: 1000 }} overlay={<span>wifi</span>} > <div className="comfort-blue" onClick={this.handleWifiHover.bind(this)}> <FontAwesome name="wifi" /> </div> </Tooltip> </div> <div className="phone">{this.props.number}</div> <Link to={`/apartments/${this.props.id}`} className="detail-btn">ะ”ะตั‚ะฐะปัŒะฝะพ</Link> </div> </div> <p className="apartment-description">{_.truncate(this.props.description, {'length': 150, 'separator': ' '})}</p> </div> ); } }
client/modules/Post/__tests__/components/PostList.spec.js
caleb272/PollIt
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import PostList from '../../components/PostList'; const posts = [ { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }, { name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" }, ]; test('renders the list', t => { const wrapper = shallow( <PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} /> ); t.is(wrapper.find('PostListItem').length, 2); });
packages/cockpit/ui/src/components/Converter.js
iurimatias/embark-framework
import PropTypes from "prop-types"; import React from 'react'; import { Card, CardBody, CardHeader, Col, FormGroup, Input, Row, Label } from 'reactstrap'; import CopyButton from './CopyButton'; import { calculateUnits } from '../services/unitConverter'; class Converter extends React.Component { constructor(props) { super(props); this.state = { etherConversions: []}; } componentDidMount() { this.setState({etherConversions: calculateUnits(this.props.baseEther, 'Ether')}); } handleOnChange(event, key) { const value = event.target.value; let newUnits; if (value.slice(-1) === '.') { // `calculateUnits()` turns `1.` to `1` which makes it impossible // for users to get beyond the first dot when typing decimal values. // That's why we bypass recalculation all together when the last character // is a dot and only update the form control in question. newUnits = this.state.etherConversions.map(unit => { if (unit.key === key) { unit.value = value; } return unit; }); this.setState({etherConversions: newUnits}); } else { newUnits = calculateUnits(value, key); this.setState({etherConversions: newUnits}); } const newBaseEther = newUnits.find(unit => unit.key === 'ether'); this.props.updateBaseEther(newBaseEther.value); } render() { return( <Row className="justify-content-md-center"> <Col xs="12" sm="9" lg="9"> <Card> <CardHeader> <strong>Ether Converter</strong> </CardHeader> <CardBody> { this.state.etherConversions.map(unit => ( <FormGroup key={unit.key}> <Label htmlFor={unit.name}>{unit.name}</Label> <div className="position-relative"> <Input id={unit.name} placeholder={unit.name} value={unit.value} onChange={e => this.handleOnChange(e, unit.key)} /> <CopyButton text={unit.value} title="Copy value to clipboard" size={2}/> </div> </FormGroup> )) } </CardBody> </Card> </Col> </Row> ); } } Converter.propTypes = { baseEther: PropTypes.string, updateBaseEther: PropTypes.func }; export default Converter;
CompositeUi/src/views/component/SectionHeader.js
kreta-io/kreta
/* * This file is part of the Kreta package. * * (c) Beรฑat Espiรฑa <[email protected]> * (c) Gorka Laucirica <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/components/_section-header.scss'; import React from 'react'; const SectionHeader = props => <div className="section-header"> <h3 className="section-header__title"> {props.title} </h3> <div className="section-header__actions"> {props.actions} </div> </div>; export default SectionHeader;
docs/src/app/components/pages/components/AppBar/Page.js
igorbt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import appBarReadmeText from './README'; import AppBarExampleIcon from './ExampleIcon'; import appBarExampleIconCode from '!raw!./ExampleIcon'; import AppBarExampleIconButton from './ExampleIconButton'; import appBarExampleIconButtonCode from '!raw!./ExampleIconButton'; import AppBarExampleComposition from './ExampleComposition'; import appBarExampleIconComposition from '!raw!./ExampleComposition'; import appBarCode from '!raw!material-ui/AppBar/AppBar'; const AppBarPage = () => ( <div> <Title render={(previousTitle) => `App Bar - ${previousTitle}`} /> <MarkdownElement text={appBarReadmeText} /> <CodeExample code={appBarExampleIconCode} title="Simple example" > <AppBarExampleIcon /> </CodeExample> <CodeExample code={appBarExampleIconButtonCode} title="Buttons example" > <AppBarExampleIconButton /> </CodeExample> <CodeExample code={appBarExampleIconComposition} title="Composition example" > <AppBarExampleComposition /> </CodeExample> <PropTypeDescription code={appBarCode} /> </div> ); export default AppBarPage;
src/layouts/CoreLayout.js
terakilobyte/rumbl_front
import React from 'react'; import 'styles/core.scss'; export default class CoreLayout extends React.Component { static propTypes = { children : React.PropTypes.element } render () { return ( <div className='page-container'> <div className='view-container'> {this.props.children} </div> </div> ); } }
src/views/pages/admin-dashboard/admin-dashboard.js
Metaburn/doocrate
import React, { Component } from 'react'; import { OrderedMap } from 'immutable'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect } from 'react-router'; import { firebaseDb } from 'src/firebase'; import { CSVLink } from 'react-csv'; import './admin-dashboard.css'; import Button from '../../components/button/button'; import { notificationActions } from '../../../notification'; import { Textbox } from 'react-inputs-validation'; import Textarea from 'react-textarea-autosize'; export class AdminDashboard extends Component { constructor() { super(...arguments); this.state = { users: OrderedMap(), query: [], isButtonsUnlocked: false, usersWhoDidntBuy: [], usersToAllowToRegisterCount: 0, successEmails: [], CSVLink: undefined, }; this.setAllUsersToHaveCreateTaskAssignPermissions = this.setAllUsersToHaveCreateTaskAssignPermissions.bind( this, ); this.unlockDashboard = this.unlockDashboard.bind(this); this.handleUsersWhoDidntBuy = this.handleUsersWhoDidntBuy.bind(this); this.handleChange = this.handleChange.bind(this); this.setUsersToDidntBuy = this.setUsersToDidntBuy.bind(this); this.setUsersAllowCreateTasks = this.setUsersAllowCreateTasks.bind(this); //this.migrateIsDone = this.migrateIsDone.bind(this); } static propTypes = { auth: PropTypes.object.isRequired, }; componentWillMount() { // We are ordering the users by creation date to use it in 3. Allowing more users to get tickets firebaseDb .collection('users') .orderBy('created', 'asc') .get() .then(querySnapshot => { const users = {}; querySnapshot.forEach(function(doc) { users[doc.id] = doc.data(); }); this.setState({ users: OrderedMap(users) }); }); } onCSVLink() { this.setState({ CSVLink: ( <span> <CSVLink className={'button-as-link'} data={this.generateUsersCSV()}> ื”ื•ืจื“ืช ื“ื•ื— ืžืฉืชืžืฉื™ื </CSVLink> </span> ), }); } componentWillReceiveProps(nextProps) {} componentDidUpdate(prevProps, prevState) { if (prevState.users !== this.state.users) { //this.setState({query}); } } isAdmin() { return this.props.auth.role === 'admin'; } generateUsersCSV = () => { const { users } = this.state; const result = [ [ 'Id', 'Created', 'Email', 'Name', 'Default Project', 'Language', 'Photo Url', 'Bio', 'Updated', ], ]; users.forEach(user => { let row = [ user.id, user.created, user.email, user.name, user.defaultProject, user.language, user.photoURL, user.bio, user.updated, ]; result.push(row); }); return result; }; render() { if (!this.isAdmin()) { return <Redirect to="/" />; } return ( <div className="admin-dashboard"> <h3>ื–ื”ื™ืจื•ืช ืื ืืชื” ืœื ื™ื•ื“ืข ืžื” ืœืขืฉื•ืช ื‘ืขืžื•ื“ ื–ื” ืขื“ื™ืฃ ืฉืชืฉืืœ ืœืคื ื™</h3> <br /> <br /> <span> ืžืกืคืจ ืžืฉืชืžืฉื™ื ื‘ืžืขืจื›ืช ืกืš ื”ื›ืœ {this.state.users.size}</span> <br /> {this.state.CSVLink ? ( this.state.CSVLink ) : ( <button className={'button-as-link'} onClick={this.onCSVLink.bind(this)} > ื”ื›ืŸ ื”ื•ืจื“ื” ืฉืœ ืจืฉื™ืžืช ื”ืžืฉืชืžืฉื™ื </button> )} <br /> <Button onClick={this.unlockDashboard}> ืืคืฉืจ ืืช ื›ืœ ื”ื›ืคืชื•ืจื™ื ื”ื‘ืื™ื - ืžื ื’ื ื•ืŸ ืื–ื”ืจื” </Button> <hr /> <br /> <h1>1.ืคืชื™ื—ืช ืืคืฉืจื•ืช ืœืžืฉืชืžืฉื™ื ืœื™ืฆื•ืจ ื•ืœืงื—ืช ืžืฉื™ืžื•ืช</h1> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setAllUsersToHaveCreateTaskAssignPermissions} > ื”ืคื•ืš ืืช ื›ืœ ื”ืžืฉืชืžืฉื™ื ืฉืœ ื”ืžืขืจื›ืช ืœื‘ืขืœื™ ื”ืจืฉืื” ืœื™ืฆื•ืจ ืžืฉื™ืžื•ืช ื•ืœืงื—ืช ืžืฉื™ืžื•ืช </Button> <hr /> <br /> <br /> <h1>2.ืงื‘ื™ืขืช ืžืฉืชืžืฉื™ื ืฉืœื ืงื ื• ื›ืจื˜ื™ืก</h1> {this.renderUsersWhoDidntBuy( 'usersWhoDidntBuy', 'ืžืฉืชืžืฉื™ื ืฉืœื ืงื ื• ื›ืจื˜ื™ืก ืžื—ื•ืœืงื™ื ื‘ืคืกื™ืง ืœื“ื•ื’ืžื [email protected],[email protected]', this.state.isButtonsUnlocked, 1, )} <span> ืกืš ืžืฉืชืžืฉื™ื ืฉื™ื•ืฉืคืขื•: {this.state.usersWhoDidntBuy.length}</span> <br /> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setUsersToDidntBuy} > ื”ื“ืœืง ืืช ื”ื“ื’ืœ ืขื‘ื•ืจ ืืช ื”ืžืฉืชืžืฉื™ื ื”ืœืœื• ืœ-DidntBuy </Button> <hr /> <br /> <br /> <h1>3.ืคืชื™ื—ืช ืืคืฉืจื•ืช ืœื™ื™ืฆืจ ืžืฉื™ืžื•ืช ืœืžืฉืชืžืฉื™ื ื”ืื—ืจื•ื ื™ื ืฉื ืจืฉืžื•</h1> {this.renderInput( 'usersToAllowToRegisterCount', 'ืžืกืคืจ ืžืฉืชืžืฉื™ื ืœืคืชื•ื— ืขื‘ื•ืจื ื”ืจืฉืžื”. ื ื’ื™ื“ 100', this.state.isButtonsUnlocked, 2, false, )} <br /> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setUsersAllowCreateTasks} > ืคืชื— ืืช ื”ืืคืฉืจื•ืช ืœืคืชื•ื— ืžืฉื™ืžื” ื•ืœืงื—ืช ืžืฉื™ืžื” ืœืื ืฉื™ื ื”ืœืœื• </Button> {this.state.successEmails && this.state.successEmails.length > 0 ? ( <div> <span>ืื™ืžื™ื™ืœื™ื ืฉื ืคืชื—ื” ืขื‘ื•ืจื ื”ืืคืฉืจื•ืช ืœื”ืจืฉื:</span> <br /> <span>{this.state.successEmails.join(',')}</span> </div> ) : ( '' )} <br /> {/*<h1>4.ืžื™ื’ืจืฆื™ื” ืœื”ื•ืกื™ืฃ ืœื›ืœ ื”ืžืฉื™ืžื•ืช ืืช ื” isDone ืคืœืื’</h1>*/} {/*<Button disabled={!this.state.isButtonsUnlocked} onClick={this.migrateIsDone}>ื‘ืฆืข ืžื™ื’ืจืฆื™ื”</Button>*/} </div> ); } renderUsersWhoDidntBuy(fieldName, placeholder, isEditable, tabIndex) { const classNames = isEditable ? ' editable' : ''; return ( <Textarea className={`changing-input${classNames}`} name={fieldName} tabIndex={tabIndex} value={this.state[fieldName]} placeholder={placeholder} ref={e => (this[fieldName + 'Input'] = e)} onChange={this.handleUsersWhoDidntBuy} onBlur={this.handleUsersWhoDidntBuy} // here to trigger validation callback on Blur onKeyUp={() => {}} // here to trigger validation callback on Key up disabled={!isEditable} /> ); } renderInput(fieldName, placeholder, isEditable, tabIndex, isAutoFocus) { const classNames = isEditable ? ' editable' : ''; return ( <Textbox className={`changing-input${classNames}`} type="text" tabIndex={tabIndex} name={fieldName} value={this.state[fieldName]} placeholder={placeholder} ref={e => (this[fieldName + 'Input'] = e)} onChange={this.handleChange} onKeyUp={() => {}} // here to trigger validation callback on Key up disabled={!isEditable} autofocus={isAutoFocus} /> ); } handleUsersWhoDidntBuy(o) { let fieldName = o.target.name; // Remove empty spaces let parsedString = o.target.value.replace(/\s/g, ''); // Break it into an array if (o.target.value) { this.setState({ [fieldName]: parsedString.split(','), }); } else { this.setState({ [fieldName]: null, }); } } handleChange(n, e) { let fieldName = e.target.name; this.setState({ [fieldName]: e.target.value, }); } // Find that user in a sluggish way findUserByEmail(userEmail) { let result = this.state.users.findEntry((user, userid) => { return user.email === userEmail; }); // Return null if empty if (!result) { return result; } // Otherwise return the key return result[0]; } /* Goes over the list of given users and allow them to create task and assign themselves */ setUsersAllowCreateTasks() { const usersCollection = firebaseDb.collection('users'); let dontHaveTicketCounter = 0; let haveTicketCounter = 0; let usersThatShouldHaveTicket = {}; this.state.users.forEach((user, userid) => { if (dontHaveTicketCounter >= this.state.usersToAllowToRegisterCount) { return; } if (!user.canCreateTask) { console.log('Dont have ticket counter - ' + dontHaveTicketCounter++); // Give him a ticket and email him and output his name console.log('Ticket for ' + user.email); usersThatShouldHaveTicket[userid] = user; } else { console.log('Have counter - ' + haveTicketCounter++); console.log('Already have ticket for ' + user.email); } }); let successCounter = 0; let successEmails = []; OrderedMap(usersThatShouldHaveTicket).forEach((user, userid) => { console.log('About to ticket ' + user.email); successEmails.push(user.email); const userDoc = usersCollection.doc(userid); userDoc .update({ canCreateTask: true, canAssignTask: true, }) .then(res => { console.log('Success ' + successCounter++ + ' ' + user.email); }) .catch(err => { console.error(err); console.log('With the following user:'); console.error(userid); console.error(user); }); }); console.log('Success emails: ' + successEmails); this.setState({ successEmails }); this.props.showSuccess( 'People who didnt have ticket and now have ' + dontHaveTicketCounter + ' People\r\n' + 'People who have ticket ' + haveTicketCounter, ); } /* Goes over the list of given users and set the didntBuy flag to true */ setUsersToDidntBuy() { const usersCollection = firebaseDb.collection('users'); let counter = 1; this.state.usersWhoDidntBuy.forEach(userWhoDidntBuyEmail => { let targetUserId = this.findUserByEmail(userWhoDidntBuyEmail); if (!targetUserId) { console.log('Cant find a user by that email: ' + userWhoDidntBuyEmail); this.props.showError( 'Cant find a user by the email ' + userWhoDidntBuyEmail + '. Check console for more info', ); } else { const userDoc = usersCollection.doc(targetUserId); userDoc .update({ didntBuy: true, }) .then(res => { console.log(counter++); }) .catch(err => { console.error(err); }); } }); this.props.showSuccess( 'Updating ' + this.state.usersWhoDidntBuy.length + ' Users... - all have flag of didntBuy. Check console and wait for it to reach ' + this.state.usersWhoDidntBuy.length, ); } /* Goes over all the users and give them permission to create task and assign tasks */ setAllUsersToHaveCreateTaskAssignPermissions() { const usersCollection = firebaseDb.collection('users'); let counter = 1; this.state.users.forEach((user, userid) => { const userDoc = usersCollection.doc(userid); userDoc .update({ canCreateTask: true, canAssignTask: true, }) .then(res => { console.log(counter++); }) .catch(err => { console.error(err); }); }); this.props.showSuccess( 'Updating ' + this.state.users.size + ' Users... - all have permission to create tasks and assign tasks. Check console and wait for it to reach ' + this.state.users.size, ); } /** * Adds a flag isDone to all the existing tasks * Done once. Stored here for future migrations till we have a proper migration system */ // migrateIsDone() { // firebaseDb.collection('projects').get().then((projectSnapshot) => { // let projectCounter = 0; // projectSnapshot.forEach((project) => { // projectCounter++; // const projectData = project.data(); // const projectTasksCollection = firebaseDb.collection('projects').doc(projectData.url).collection('tasks'); // projectTasksCollection.get().then((tasksSnapshot) => { // let counter = 1; // tasksSnapshot.forEach((task) => { // const taskId = task.id; // projectTasksCollection.doc(taskId).update({ // isDone: false // }).then(res => { // counter++; // console.log("User " + projectCounter + ": Counter " + counter); // }).catch(err => { // console.error(err); // }); // }) // }); // debugger; // // }) // // }); // // } unlockDashboard() { this.setState({ isButtonsUnlocked: !this.state.isButtonsUnlocked }); } } //===================================== // CONNECT //------------------------------------- const mapStateToProps = state => { return { tasks: state.tasks.list, auth: state.auth, }; }; const mapDispatchToProps = Object.assign({}, notificationActions); export default connect(mapStateToProps, mapDispatchToProps)(AdminDashboard);
website/src/pages/index.js
wix/react-native-navigation
import React from 'react'; import { Redirect } from '@docusaurus/router'; function Home() { return <Redirect to="/react-native-navigation/docs/before-you-start/" />; } export default Home;
app/src/client/components/app/Notifications.js
dvdschwrtz/DockDev
import React from 'react'; import {Link} from 'react-router'; // import { remote } from 'electron'; const Notifications = ({ DOToken, updateToken }) => ( <div className="full-page"> <div className="notification-content"> <div className="list-group"> <a href="#" className="list-group-item active"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#" className="list-group-item"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#" className="list-group-item"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> </div> </div> </div> ); Notifications.propTypes = { updateToken: React.PropTypes.func, DOToken: React.PropTypes.string, }; export default Notifications;
src/components/search/AccountFilter.js
whphhg/vcash-ui
import React from 'react' import { translate } from 'react-i18next' import { inject, observer } from 'mobx-react' /** Ant Design */ import Select from 'antd/lib/select' @translate(['common']) @inject('send', 'wallet') @observer class AccountFilter extends React.Component { constructor(props) { super(props) this.t = props.t this.send = props.send this.wallet = props.wallet } render() { return ( <Select onChange={acc => this.send.setSpendFrom(acc)} optionFilterProp="children" size="small" style={{ width: '140px' }} value={this.send.spend.fromAccount} > <Select.Option disabled={ this.send.recipients.size > 1 && this.send.spend.utxo.length === 0 } value="*ANY*" > {this.t('any')} </Select.Option> <Select.Option value="*DEFAULT*">{this.t('default')}</Select.Option> {this.wallet.accNames.map(acc => ( <Select.Option key={acc} value={acc}> {acc} </Select.Option> ))} </Select> ) } } export default AccountFilter
src/step-23/ReOrganize.js
gufsky/react-native-workshop
import React, { Component } from 'react' import Highlight from 'react-syntax-highlight' import Note from '../Note' import structurePng from './Structure.png' const HomeScreen = `import React from 'react' import { connect } from 'react-redux' import { searchBars } from './../store/actions/actions' import { AppRegistry, StyleSheet, Text, TextInput, View, Image, TouchableOpacity } from 'react-native' import * as colors from './../styles/colors' class HomeScreen extends React.Component { static navigationOptions () { return { title: 'Welcome' } } constructor (props) { super(props) this.clickHandler = this.clickHandler.bind(this) navigator.geolocation.getCurrentPosition(data => this.state.location = data, error => console.log('GEO ERROR', error)) this.state = { searchString: '', location: null } console.log('CURRENT POSITION: ', this.state.location) } clickHandler () { const { navigation, doSearch } = this.props const { searchString, location } = this.state doSearch(searchString, location.coords.latitude, location.coords.longitude).then(() => navigation.navigate('Map', { searchString: this.state.searchString })) } render () { console.log('search props', this.state) return ( <View style={styles.container}> <View style={styles.row}> <Image source={require('./../assets/images/Beer.png')} style={styles.mainIcon} /> <Image source={require('./../assets/images/Wine.png')} style={styles.mainIcon} /> <Image source={require('./../assets/images/Martini.png')} style={styles.mainIcon} /> </View> <Text style={styles.welcome}>Begin Your Adventure</Text> <View style={{ flexDirection: 'row' }}> <View style={styles.searchWrap}> <TextInput style={styles.search} underlineColorAndroid='transparent' placeholder='Search for beer, wine, or cocktail' placeholderTextColor='#f7f7f7' onChangeText={text => this.setState({ searchString: text })} value={this.state.searchString} /> </View> <TouchableOpacity onPress={this.clickHandler} style={{ flex: 1, alignItems: 'center', padding: 5 }} > <Image source={require('./../assets/images/Search.png')} style={{ height: 30, width: 30, marginTop: -5 }} /> </TouchableOpacity> </View> </View> ) } } const STANDARD_VERT_SPACING = 25 const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.PRIMARY_PURPLE, padding: 20 }, row: { flexDirection: 'row', marginBottom: 15 }, mainIcon: { height: 80, width: 80 }, searchWrap: { height: 30, flex: 5, backgroundColor: '#986FBF', borderWidth: 0.5, borderColor: colors.WHITE, borderRadius: 2, marginBottom: STANDARD_VERT_SPACING, padding: 5, paddingLeft: 10 }, search: { flex: 1, // needed for IOS text to center vertically fontSize: 14, color: colors.WHITE }, welcome: { color: colors.WHITE, fontSize: 20, textAlign: 'center', margin: 10, marginBottom: STANDARD_VERT_SPACING }, instructions: { textAlign: 'center', color: colors.WHITE, marginBottom: 5 } }) export default connect(null, dispatch => { return { doSearch: (text, lat, long) => dispatch(searchBars(text, lat, long)) } })(HomeScreen)` const indexJs = `import React from 'react' import { AppRegistry } from 'react-native' import { StackNavigator } from 'react-navigation' import { fetchInitialState } from './store/actions/actions'; import MapScreen from './components/Map' import HomeScreen from './components/HomeScreen' const Routes = StackNavigator({ Home: { screen: HomeScreen }, Map: { screen: MapScreen } }, { headerMode: 'none' }) export default class App extends React.Component { render () { return ( <Routes /> ) } } AppRegistry.registerComponent('barfinder', () => App) ` const packageJSON = `{ "name": "barfinder", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest", "lint": "standard --fix" }, "dependencies": { "lodash": "^4.17.4", "react": "16.0.0-alpha.12", "react-native": "0.48.3", "react-native-configs": "^1.1.0", "react-native-maps": "^0.16.4", "react-navigation": "^1.0.0-beta.11", "react-redux": "^5.0.6", "redux": "^3.7.2", "redux-thunk": "^2.2.0" }, "devDependencies": { "babel-jest": "21.0.2", "babel-preset-react-native": "4.0.0", "jest": "21.1.0", "react-test-renderer": "16.0.0-alpha.12", "standard-react-native": "^1.0.1" }, "jest": { "preset": "react-native" } } ` class SearchUiView extends Component { render() { return ( <div className="general"> <h1>16. Let's Start by Reorganizing!</h1> <p>In the next few steps we will be cleaning up some code from the last workshop, adding the components we need for our search screen, and the interactions and supporting routes for the map screen, and detail screen.</p> <h2>Project Structure</h2> <p>Setup your project with the following files and folders:</p> <p><b>2 key folders added </b></p> <ul> <li>/config</li> <li>/store</li> </ul> <img src={structurePng} style={{height: '60rem'}} /> <p>Update package.json to include the redux and config dependencies</p> <Highlight lang='json' value={packageJSON} /> <p>npm install</p> <h2>Move HomeScreen to its own component</h2> <p>Let's start by making our entry files a bit more readable</p> <ul className="setup__steps"> <li> <p>Create a component file called HomeScreen.js and add migrate the code from entry to our new component.</p> <Highlight lang='javascript' value={HomeScreen} /> </li> <li> <p>Now update index.ios.js and index.android.ios</p> <Highlight lang='javascript' value={indexJs} /> </li> </ul> <p>We are now ready to implement our redux store!</p> </div> ) } } export default SearchUiView