path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/app/views/myRecipes.js
nazar/soapee-ui
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import { Link } from 'react-router'; import meStore from 'stores/me'; import meActions from 'actions/me'; import RecipeListItem from 'components/recipeListItem'; import Spinner from 'components/spinner'; export default React.createClass( { mixins: [ Reflux.connect( meStore, 'profile' ) ], componentDidMount() { meActions.getMyRecipes(); }, render() { document.title = 'Soapee - My Recipes'; return ( <div id="my-recipes"> <legend>My Recipes</legend> { this.renderLoading() } { this.renderRecipes() } </div> ); }, renderLoading() { if ( !(this.state.profile.myRecipes) ) { return <Spinner />; } }, renderRecipes() { let lengthRecipes = _.get(this.state.profile.myRecipes, 'length', 0); if ( lengthRecipes > 0 ) { return _( this.state.profile.myRecipes ) .sortBy( 'created_at' ) .reverse() .map( this.renderRecipe ) .value(); } else if ( lengthRecipes === 0 ) { return ( <div className="jumbotron"> No recipes found. Use the <Link to="calculator">calculator</Link> to add recipes to your profile. </div> ); } }, renderRecipe( recipe ) { return ( <div key={ `recipe-${ recipe.id }` }> <RecipeListItem recipe={recipe} /> </div> ); } } );
.storybook/LoginStories.js
buaya91/just-us-blog
import React from 'react' import { storiesOf, action } from '@kadira/storybook' import LoginForm from '../src/login/LoginForm' import LoginPopUp from '../src/login/LoginPopUp' import { actions } from './testProps' storiesOf('Login', module) .add('form only', () => ( <LoginForm /> )) .add('with Popup', () => ( <LoginPopUp actions={actions} show /> ))
packages/material-ui-icons/src/ExpandLess.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z" /></g> , 'ExpandLess');
imports/ui/containers/AdminContainer.js
scimusmn/map-stories
/** * Container for the admin view where we control and manage image data */ // import React from 'react'; import { Meteor } from 'meteor/meteor'; import { composeWithTracker } from 'react-komposer'; import { Loading } from '../components/loading.js'; import { Images } from '../../api/images/images.js'; import { ImageFiles } from '../../api/imageFiles/imageFiles'; import { Places } from '../../api/places/places.js'; import AdminListWrapper from '../components/AdminListWrapper'; /** * Provide data for the list of places and images */ const composer = (props, onData) => { // Create a subscription of places and images const subscription = Meteor.subscribe('placesImages'); if (subscription.ready()) { const places = Places.find({}).fetch(); const images = Images.find({}).fetch(); const imageFiles = ImageFiles.find({}).fetch(); onData(null, { places, images, imageFiles }); } }; export default composeWithTracker(composer, Loading)(AdminListWrapper);
test/specs/button/button.spec.js
rafaelfbs/realizejs
import React from 'react'; import { Button } from 'components'; import { assert } from 'chai'; import { shallow, mount } from 'enzyme'; describe('<Button/>', () => { it('exists', () => { assert(Button); }); it('renders with the default props', () => { const content = shallow( <Button /> ); assert(content.find('Button')); }); it('renders a button with a link', () => { const content = mount( <Button name='Go to Google!' element='a' href='http://www.google.com.br' /> ); assert.equal(content.find('a').text(), "Go to Google!"); }) });
frontend/tests/components/options/forum-options.js
1905410/Misago
import assert from 'assert'; import React from 'react'; // jshint ignore:line import ForumOptions from 'misago/components/options/forum-options'; // jshint ignore:line import snackbar from 'misago/services/snackbar'; import store from 'misago/services/store'; import * as testUtils from 'misago/utils/test-utils'; let snackbarStore = null; let user = testUtils.mockUser(); describe("Forum Options Form", function() { beforeEach(function() { snackbarStore = testUtils.snackbarStoreMock(); snackbar.init(snackbarStore); testUtils.initEmptyStore(store); }); afterEach(function() { testUtils.unmountComponents(); testUtils.snackbarClear(snackbar); $.mockjax.clear(); }); it("renders", function(done) { /* jshint ignore:start */ testUtils.render(<ForumOptions user={user} />); /* jshint ignore:end */ testUtils.onElement('#test-mount .form-horizontal', function() { assert.ok(true, "component renders"); done(); }); }); it("handles backend rejection", function(done) { $.mockjax({ url: user.api_url.options, status: 400, responseText: { detail: "Lol nope!" } }); /* jshint ignore:start */ testUtils.render(<ForumOptions user={user} />); /* jshint ignore:end */ snackbarStore.callback(function(message) { assert.deepEqual(message, { message: "Please reload page and try again.", type: 'error' }, "error message was shown"); done(); }); testUtils.onElement('#test-mount form', function() { testUtils.simulateSubmit('#test-mount form'); }); }); it("handles backend error", function(done) { $.mockjax({ url: user.api_url.options, status: 500 }); /* jshint ignore:start */ testUtils.render(<ForumOptions user={user} />); /* jshint ignore:end */ snackbarStore.callback(function(message) { assert.deepEqual(message, { message: "Unknown error has occured.", type: 'error' }, "error message was shown"); done(); }); testUtils.onElement('#test-mount form', function() { testUtils.simulateSubmit('#test-mount form'); }); }); it("submits successfully", function(done) { $.mockjax({ url: user.api_url.options, status: 200, responseText: { detail: 'ok' } }); /* jshint ignore:start */ testUtils.render(<ForumOptions user={user} />); /* jshint ignore:end */ snackbarStore.callback(function(message) { assert.deepEqual(message, { message: "Your forum options have been changed.", type: 'success' }, "success message was shown"); done(); }); testUtils.onElement('#test-mount form', function() { testUtils.simulateSubmit('#test-mount form'); }); }); });
src/js/modules/Home.js
fredyagomez/reactjs-D3-V4-grommet
import React from 'react'; import Section from 'grommet/components/Section'; import Tiles from 'grommet/components/Tiles'; import Tile from 'grommet/components/Tile'; import Header from 'grommet/components/Header'; import Footer from 'grommet/components/Footer'; import Image from 'grommet/components/Image'; import NavLink from './NavLink'; export default React.createClass({ contextTypes: { router: React.PropTypes.object }, handleSubmit(event) { event.preventDefault(); const path = `/Taxonomy`; this.context.router.push(path); }, handleSubmit2(event) { event.preventDefault(); const path = `/Discovery`; this.context.router.push(path); }, handleSubmit3(event) { event.preventDefault(); const path = `/Policy`; this.context.router.push(path); }, handleSubmit4(event) { event.preventDefault(); //const userName = event.target.elements[0].value; //const repo = event.target.elements[1].value; const path = `/Change`; //const path = `/repos/${userName}/${repo}`; console.log(path); this.context.router.push(path); }, handleSubmit5(event) { event.preventDefault(); const path = `/Support`; //const path = `/repos/${userName}/${repo}`; console.log(path); this.context.router.push(path); }, render() { return ( <div> <Section align="start" pad={{"horizontal": "medium", "vertical": "medium", "between": "small"}} > <Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal" responsive={true}> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit}> <Header> <NavLink to="/Taxonomy"> <b>Tile 1</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_data.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit2}> <Header> <NavLink to="/Discovery"> <b>Tile 2</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> </Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal" > <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_ux.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit3}> <Header> <NavLink to="/Policy"> <b>Tile 3</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_demos.jpg" /> </Tile> </Tiles> <Tiles fill={true} colorIndex="accent-2" flush={true} justify="center" full="horizontal"> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit4}> <Header> <NavLink to="/Change"> <b>Tile 4</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> <Tile colorIndex="neutral-2" pad={{"horizontal": "medium"}}> <Image src="img/tile_strategy.jpg" /> </Tile> <Tile colorIndex="neutral-1" fill={false} flush={true} pad={{"horizontal": "medium"}} onClick={this.handleSubmit5}> <Header> <NavLink to="/Support"> <b>Tile 5</b> </NavLink> </Header> <Footer> Sub-title </Footer> </Tile> </Tiles> </Tiles> </Section> </div>); } });
src/components/CompanyAndJobTitle/WorkExperiences/ExperienceEntry.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import cn from 'classnames'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import faLock from '@fortawesome/fontawesome-free-solid/faLock'; import { Heading, P } from 'common/base'; import i from 'common/icons'; import styles from './WorkExperiences.module.css'; import { formatSalary, formatSalaryRange } from 'common/formatter'; import { formatCreatedAt, formatWeekWorkTime } from './helper'; const createLinkTo = ({ pageType, id }) => ({ pathname: `/experiences/${id}`, state: { pageType }, }); const SNIPPET_SIZE = 30; const ExperienceEntry = ({ pageType, data: { id, company: { name: companyName } = {}, job_title: { name: jobTitle } = {}, created_at: createdAt, sections: [section], week_work_time: weekWorkTime, salary, recommend_to_others: recommendToOthers, }, size, canView, }) => ( <div className={cn(styles.container, styles[size])}> <Link to={createLinkTo({ id, pageType })}> <section className={styles.contentWrapper}> <div className={styles.labels}> <P size="s" className={styles.date}> 工作經驗 · {formatCreatedAt(createdAt)} </P> <div className={styles.salaryRecommendWrapper}> {weekWorkTime && canView && ( <div className={styles.weekWorkTime}> <i.Clock /> {formatWeekWorkTime(weekWorkTime)} </div> )} {salary && ( <div className={cn(styles.salary, { [styles.locked]: !canView, })} > {canView ? ( <React.Fragment> <i.Coin /> {formatSalary(salary)} </React.Fragment> ) : ( <React.Fragment> <FontAwesomeIcon icon={faLock} /> {formatSalaryRange(salary)} </React.Fragment> )} </div> )} <div className={styles.recommendToOthers}> {recommendToOthers === 'yes' ? <i.Good /> : <i.Bad />} {recommendToOthers === 'yes' ? '推' : '不推'} </div> </div> </div> <Heading Tag="h2" size={size === 'l' ? 'sl' : 'sm'} className={styles.heading} > {companyName} {jobTitle} </Heading> <div className={styles.snippetWrapper}> <span className={styles.snippet}> {section.content.slice(0, SNIPPET_SIZE)}.... </span> <span className={cn(styles.readmore, { [styles.locked]: !canView, })} > {`閱讀更多${canView ? '' : '並解鎖'}`} </span> </div> </section> </Link> </div> ); ExperienceEntry.propTypes = { data: PropTypes.object.isRequired, size: PropTypes.oneOf(['s', 'm', 'l']), canView: PropTypes.bool.isRequired, }; ExperienceEntry.defaultProps = { size: 'm', }; export default ExperienceEntry;
src/components/type-list.js
tylerchilds/pokedex
import React from 'react'; import TypeLink from '../components/type-link'; import ALL_TYPES from '../data/types'; export default class TypeList extends React.Component { render() { return ( <div> {ALL_TYPES.map((type, key) => ( <TypeLink type={type} key={key} /> ))} </div> ); } }
src/client/assets/js/features/driver/components/Data/Data.js
me-box/databox-sdk
import React from 'react'; import DataType from './DataType'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { actionCreators as driverActions, selector } from '../../'; @connect(selector, (dispatch) => { return{ actions: bindActionCreators(driverActions, dispatch), } }) export default class Data extends React.Component { constructor(props){ super(props); this.state={showdatatypes:false, add:false} this.renderDataTypes = this.renderDataTypes.bind(this); this.renderSchema = this.renderSchema.bind(this); this.addSchema = this.addSchema.bind(this); } addSchema(id){ if (this.state.add){ this.props.actions.addSchema(id); } this.setState({showdatatypes:false, add:false}); } renderDataTypes(){ const {driver:{dataTypes}} = this.props; const items = dataTypes.map((id)=>{ return <DataType key={id} id={id} addSchema={this.addSchema}/> }) return <div className="modal"> <div className="modal-content"> <div className="modal-header"> <span className="close" onClick={()=>this.setState({showdatatypes:false})}>&times;</span> <h2>select data type</h2> </div> <div className="modal-body"> <div className="datagrid"> {items} </div> </div> <div className="modal-footer"> </div> </div> </div> } renderSchema(){ const {driver:{schema}} = this.props; const addnew = <tr> <td><input type="text" placeholder="field name"/></td> <td> <div className="option"> <label onClick={()=>this.setState({showdatatypes:true, add:true})}>field type</label> </div> </td> <td> <div className="optionsgrid"> <div className="option"><label>blank</label></div> <div className="option"><input type="text" placeholder="0"/></div> <div className="option"><label>fn</label></div> <div className="option"><input type="text" placeholder="fn"/></div> <div className="option"><span className="close">&times;</span></div> </div> </td> </tr> const existing = schema.map((s,i)=>{ return <tr key={i}> <td><input type="text" placeholder="field name"/></td> <td> <div className="option"> <label onClick={()=>this.setState({showdatatypes:true, add:false})}>{s.schema.name}</label> </div> </td> <td> <div className="optionsgrid"> <div className="option"><label>blank</label></div> <div className="option"><input type="text" placeholder="0"/></div> <div className="option"><label>fn</label></div> <div className="option"><input type="text" placeholder="fn"/></div> <div className="option"><span className="close">&times;</span></div> </div> </td> </tr> }); const rows = [...existing, addnew]; return <table className="drivertable"> <thead> <tr> <th> field name </th> <th> type </th> <th> options </th> </tr> </thead> <tbody> {rows} </tbody> </table> } render(){ return <div> <div className="panel"> <div className="cell"> <div className="description"> Use this to describe the <strong>structure</strong> of the data that is emitted from your driver. This schema will also be used to create synthetic <strong> test data </strong> to test the driver in the sdk. </div> <div className="attribute"> {this.renderSchema()} </div> </div> </div> <div className="panel"> <div className="cell"> <div className="description"> Data <strong>format</strong> </div> <div className="attribute"> <div className="attribute-grid"> <div className="driverbutton">JSON</div> <div className="driverbutton">XML</div> <div className="driverbutton">CSV</div> </div> </div> </div> </div> <div className="panel"> <div className="cell"> <div className="description"> Data <strong>frequency</strong> </div> <div className="attribute"> </div> </div> </div> {this.state.showdatatypes && this.renderDataTypes()} </div> } }
src/Parser/DemonHunter/Shared/Modules/Items/SoulOfTheSlayer.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import ItemLink from 'common/ItemLink'; import SPECS from 'common/SPECS'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE'; const debug = false; /** * Equip: Gain one of the following talents based on your specialization: * Havoc: First Blood * Vengeance: Fallout */ class SoulOfTheSlayer extends Analyzer { static dependencies = { combatants: Combatants, }; on_initialized() { this.active = this.combatants.selected.hasFinger(ITEMS.SOUL_OF_THE_SLAYER.id); //Checks which spec has the ring equipped and then sets option1 or option2 accordingly - aswell as sets up the check for if they've picked another talent switch (this.combatants.selected.spec) { case SPECS.HAVOC_DEMON_HUNTER: this.talentGained = SPELLS.FIRST_BLOOD_TALENT.id; this.option1 = SPELLS.CHAOS_CLEAVE_TALENT.id; this.option2 = SPELLS.BLOODLET_TALENT.id; break; case SPECS.VENGEANCE_DEMON_HUNTER: this.talentGained = SPELLS.FALLOUT_TALENT.id; this.option1 = SPELLS.FEAST_OF_SOULS_TALENT.id; this.option2 = SPELLS.BURNING_ALIVE_TALENT.id; break; default: debug && console.log(' NO SPEC DETECTED'); break; } this.hasPickedOtherTalent = this.combatants.selected.hasTalent(this.option1) || this.combatants.selected.hasTalent(this.option2); } item() { return { item: ITEMS.SOUL_OF_THE_SLAYER, result: <Wrapper>This gave you <SpellLink id={this.talentGained} icon />.</Wrapper>, }; } get suggestionThresholds() { return { actual: this.hasPickedOtherTalent, isEqual: false, style: 'boolean', }; } suggestions(when) { when(this.suggestionThresholds).isFalse().addSuggestion((suggest) => { return suggest(<Wrapper>When using <ItemLink id={ITEMS.SOUL_OF_THE_SLAYER.id} /> please make sure to pick another talent in the talent row. Your choices are <SpellLink id={this.option1} /> or <SpellLink id={this.option2} />.</Wrapper>) .icon(ITEMS.SOUL_OF_THE_SLAYER.icon) .staticImportance(SUGGESTION_IMPORTANCE.MAJOR); }); } } export default SoulOfTheSlayer;
bdocker/bnodejs/gatsby/web/pages/less.js
waterbolik/prestudy
import React from 'react' import './example.less' import Helmet from 'react-helmet' import { config } from 'config' export default class Less extends React.Component { render () { return ( <div> <Helmet title={`${config.siteTitle} | Hi lessy friends`} /> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-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> ) } }
pootle/static/js/auth/components/AuthContent.js
ta2-1/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import assign from 'object-assign'; import React from 'react'; import { PureRenderMixin } from 'react-addons-pure-render-mixin'; const AuthContent = React.createClass({ propTypes: { children: React.PropTypes.node, style: React.PropTypes.object, }, mixins: [PureRenderMixin], render() { // FIXME: use flexbox when possible const outer = assign({ display: 'table', height: '22em', width: '100%', }, this.props.style); const style = { outer, inner: { display: 'table-cell', verticalAlign: 'middle', }, }; return ( <div style={style.outer}> <div style={style.inner}> {this.props.children} </div> </div> ); }, }); export default AuthContent;
examples/with-why-did-you-render/scripts/wdyr.js
flybayer/next.js
import React from 'react' if (process.env.NODE_ENV === 'development') { if (typeof window !== 'undefined') { const whyDidYouRender = require('@welldone-software/why-did-you-render') whyDidYouRender(React, { trackAllPureComponents: true, }) } }
app/containers/DevTools.js
Kahrstrom/skillocate-react
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> );
packages/material-ui-icons/src/BatteryCharging80Sharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M17 4h-3V2h-4v2H7v5h4.93L13 7v2h4V4z" /><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v13h10V9h-4v3.5z" /></React.Fragment> , 'BatteryCharging80Sharp');
packages/stdind/src/main.js
istarkov/pbl
import { AppContainer } from 'react-hot-loader'; import { Observable } from 'rxjs'; import React from 'react'; import { render } from 'react-dom'; import webfontloader from 'webfontloader'; import setObservableConfig from 'recompose/setObservableConfig'; import 'normalize.css/normalize.css'; import './main.sass'; import App from './App'; const mountNode = document.getElementById('app'); setObservableConfig({ fromESObservable: Observable.from, }); webfontloader.load({ google: { families: ['Roboto Mono'], }, }); render( <AppContainer> <App /> </AppContainer>, mountNode, ); if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; // eslint-disable-line render( <AppContainer> <NextApp /> </AppContainer>, mountNode, ); }); }
src/pages/Login.js
prodigalyijun/demo-by-antd
import React from 'react'; import { Icon, Form, Input, Button, message } from 'antd'; import { post } from '../utils/request'; import style from '../styles/login-page.less'; const FormItem = Form.Item; class Login extends React.Component { constructor() { super(); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { post('http://localhost:3000/login', values) .then((res) => { if (res) { message.info('登录成功'); this.context.router.push('/'); } else { message.info('登录失败,账号或密码错误'); } }); } }); } render() { const { form } = this.props; const { getFieldDecorator } = form; return ( <div className={style.wrapper}> <div className={style.body}> <header className={style.header}>ReactManager </header> <section className={style.form}> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('account', { rules: [ { required: true, message: '请输入管理员账号', type: 'string' } ] })( <Input type="text" addonBefore={<Icon type="user" />} /> )} </FormItem> <FormItem> {getFieldDecorator('password', { rules: [ { required: true, message: '请输入密码', type: 'string' } ] })( <Input type="password" addonBefore={<Icon type="lock" />} /> )} </FormItem> <Button className={style.btn} type="primary" htmlType="submit">Sign In</Button> </Form> </section> </div> </div> ); } } Login.contextTypes = { router: React.PropTypes.object.isRequired }; Login = Form.create()(Login); export default Login;
src/containers/Forms/FormsWithValidation/index.js
EncontrAR/backoffice
import React, { Component } from 'react'; import Form from '../../../components/uielements/form'; import Input from '../../../components/uielements/input'; import PageHeader from '../../../components/utility/pageHeader'; import Box from '../../../components/utility/box'; import LayoutWrapper from '../../../components/utility/layoutWrapper'; import IntlMessages from '../../../components/utility/intlMessages'; const FormItem = Form.Item; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 5 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 12 }, }, }; export default class FormsWithValidation extends Component { render() { return ( <LayoutWrapper> <PageHeader>{<IntlMessages id="forms.formsWithValidation.header" />}</PageHeader> <Box> <Form> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.failLabel" />} validateStatus="error" help={<IntlMessages id="forms.formsWithValidation.failHelp" />} > <Input placeholder="unavailable choice" id="error" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.warningLabel" />} validateStatus="warning" > <Input placeholder="Warning" id="warning" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.ValidatingLabel" />} hasFeedback validateStatus="validating" help={<IntlMessages id="forms.formsWithValidation.ValidatingHelp" />} > <Input placeholder="I'm the content is being validated" id="validating" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.SuccessLabel" />} hasFeedback validateStatus="success" > <Input placeholder="I'm the content" id="success" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.WarninghasFeedbackLabel" />} hasFeedback validateStatus="warning" > <Input placeholder="Warning" id="warning" /> </FormItem> <FormItem {...formItemLayout} label={<IntlMessages id="forms.formsWithValidation.FailhasFeedbackLabel" />} hasFeedback validateStatus="error" help={<IntlMessages id="forms.formsWithValidation.FailhasFeedbackHelp" />} > <Input placeholder="unavailable choice" id="error" /> </FormItem> </Form> </Box> </LayoutWrapper> ); } }
examples/named-components/render/client.js
dlmr/react-router-redial
import { useRedial } from 'react-router-redial'; import React from 'react'; import { render } from 'react-dom'; import { Router, browserHistory, applyRouterMiddleware } from 'react-router'; // Render the app client-side to a given container element: export default (container, routes) => { const forcePageReloadOnError = true; const goBackOnError = false; // Function that can be used as a setting for useRedial function onError(err, { abort, beforeTransition, reason, router }) { if (process.env.NODE_ENV !== 'production') { console.error(reason, err); } // We only what to do this if it was a blocking hook that failed if (beforeTransition) { if (forcePageReloadOnError && reason === 'other') { window.location.reload(); } else if (goBackOnError && reason !== 'location-changed') { router.goBack(); } // Abort current loading automatically abort(); } } const component = ( <Router history={browserHistory} routes={routes} render={applyRouterMiddleware(useRedial({ beforeTransition: ['fetch'], afterTransition: ['defer', 'done'], parallel: true, initialLoading: () => <div>Loading…</div>, onError, }))} /> ); // Render app to container element: render(component, container); };
src/client.js
createspb/obsvtr
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; import makeRouteHooksSafe from './helpers/makeRouteHooksSafe'; const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), createHistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <ReduxRouter routes={getRoutes(store)} /> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__) { const DevTools = require('./components/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
packages/wix-style-react/src/ContactItemBuilder/ContactItemBuilder.js
wix/wix-style-react
import React from 'react'; import { classes } from './ContactItemBuilder.st.css'; import Avatar from '../Avatar/Avatar'; import Text from '../Text'; import { dataHooks } from './ContactItemBuilderDataHooks'; import PropTypes from 'prop-types'; import deprecationLog from '../utils/deprecationLog'; export const ContactItem = props => { deprecationLog( 'This component is deprecated. Please use ListItemSelect instead', ); return ( <div className={classes.contactItemOption}> <div className={classes.avatar}> <Avatar name={props.title} size="size30" imgProps={{ src: props.imageUrl }} data-hook={dataHooks.pickerOptionAvatar} /> </div> <div className={classes.contactItemTitles}> <Text ellipsis size="medium" weight="normal" secondary={!props.selected} light={props.selected} dataHook={dataHooks.pickerOptionTitle} > {props.title} </Text> {props.subtitle ? ( <Text ellipsis size="small" weight="thin" secondary={!props.selected} light={props.selected} dataHook={dataHooks.pickerOptionSubtitle} > {props.subtitle} </Text> ) : null} </div> </div> ); }; ContactItem.propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string, imageUrl: PropTypes.string, }; export const contactItemBuilder = ({ id, title, subtitle, imageUrl, disabled, }) => ({ id, disabled, value: ({ selected }) => ( <ContactItem title={title} subtitle={subtitle} imageUrl={imageUrl} selected={selected} /> ), });
src/containers/Contact/index.js
benceg/dani
import React from 'react'; import { asyncConnect } from 'redux-connect'; import get from 'lodash/get'; import Color from 'color'; import { componentWillMount } from 'react-lifecycle-decorators'; import { fetchContent, resetForm, sendForm } from './actions'; import ReactMarkdown from 'react-markdown'; import Helmet from 'react-helmet'; import AppView from '../../components/AppView'; import Main from '../../components/Main'; import Sidebar from '../../components/Sidebar'; import Image from '../../components/Image'; import ContactForm from '../../components/ContactForm'; import routerLink from '../../helpers/routerLink'; if (process.env.WEBPACK) require('./stylesheet.styl'); const tint = '#41396b'; const handleSubmit = (dispatch) => (fields) => dispatch(sendForm(fields)); const Contact = ({ body, image, title, error, sent, dispatch }) => <AppView className='Contact' tint={tint} title={title}> <Helmet meta={[{name: 'og:image', content: `${get(image, 'fields.file.url')}?fit=thumb&w=600&h=600`}]} style={[{cssText: `.Contact [type="submit"] { background-color: ${Color(tint).darken(0.5).hexString()}; }`}]} /> <Main> <Image alt={title} src={get(image, 'fields.file.url')} /> </Main> <Sidebar tint={tint}> <article> <h1>{title}</h1> <section> <ReactMarkdown source={body || ''} escapeHtml={true} renderers={{Link: routerLink}} /> </section> {error && <p className='error-message'>Sorry, there was a problem sending your form.</p>} {sent && <p className='success-message'>Thank you for your message.</p>} {!sent && <ContactForm action='/send' method='post' handleSubmit={handleSubmit(dispatch)} />} </article> </Sidebar> </AppView> Contact.propTypes = { loaded: React.PropTypes.bool.isRequired, body: React.PropTypes.string, image: React.PropTypes.object, title: React.PropTypes.string.isRequired, sent: React.PropTypes.bool, error: React.PropTypes.bool }; const mapStateToProps = ({ contact }) => ({ loaded: contact.loaded, body: contact.content.body, image: contact.content.image, title: contact.content.title, sent: contact.sent, error: contact.error }); export default asyncConnect( [{ promise: ({ store: { dispatch } }) => dispatch(fetchContent()) }], mapStateToProps )(componentWillMount(({ dispatch }) => dispatch(resetForm()))(Contact));
src/components/LayerStylesCarousel/LayerStyleItem.js
MinisterioPublicoRJ/inLoco-2.0
import React from 'react' const LayerStyleItem = ({layer, style, index, onStyleClick}) => { let itemClassName = 'layer-styles-carousel--list-item' if (layer && layer.selectedLayerStyleId === index) { itemClassName += ' selected' } function styleClick() { return onStyleClick(layer, index) } return ( <li className={itemClassName} onClick={styleClick}> { style ? <img className="layer-styles-carousel--image" src={style.thumb} alt={style.title}/> : '' } </li> ) } export default LayerStyleItem
pkg/interface/link/src/js/components/lib/channel-sidebar.js
jfranklin9000/urbit
import React, { Component } from 'react'; import { Route, Link } from 'react-router-dom'; import { GroupItem } from './group-item'; import { SidebarInvite } from '/components/lib/sidebar-invite'; import { Welcome } from '/components/lib/welcome'; import { alphabetiseAssociations } from '../../lib/util'; export class ChannelsSidebar extends Component { // drawer to the left render() { const { props, state } = this; let sidebarInvites = Object.keys(props.invites) .map((uid) => { return ( <SidebarInvite uid={uid} invite={props.invites[uid]} api={props.api} /> ); }); let associations = !!props.associations.contacts ? alphabetiseAssociations(props.associations.contacts) : {}; let groupedChannels = {}; [...props.listening].map((path) => { let groupPath = !!props.associations.link[path] ? props.associations.link[path]["group-path"] : ""; if (groupPath.startsWith("/~/")) { if (groupedChannels["/~/"]) { let array = groupedChannels["/~/"]; array.push(path); groupedChannels["/~/"] = array; } else { groupedChannels["/~/"] = [path]; }; } if (groupPath in associations) { if (groupedChannels[groupPath]) { let array = groupedChannels[groupPath]; array.push(path); groupedChannels[groupPath] = array; } else { groupedChannels[groupPath] = [path]; } } }); let selectedGroups = !!props.selectedGroups ? props.selectedGroups : []; let i = -1; const groupedItems = Object.keys(associations) .filter((each) => { if (selectedGroups.length === 0) { return true; }; let selectedPaths = selectedGroups.map((e) => { return e[0]; }); return selectedPaths.includes(each); }) .map((each) => { let channels = groupedChannels[each]; if (!channels || channels.length === 0) return; i++; if ((selectedGroups.length === 0) && groupedChannels["/~/"] && groupedChannels["/~/"].length !== 0) { i++; } return ( <GroupItem key={i} index={i} association={associations[each]} linkMetadata={props.associations["link"]} channels={channels} selected={props.selected} links={props.links} /> ) }); if ((selectedGroups.length === 0) && groupedChannels["/~/"] && groupedChannels["/~/"].length !== 0) { groupedItems.unshift( <GroupItem key={"/~/"} index={0} association={"/~/"} linkMetadata={props.associations["link"]} channels={groupedChannels["/~/"]} selected={props.selected} links={props.links} /> ) } let activeClasses = (this.props.active === "collections") ? " " : "dn-s "; let hiddenClasses = true; if (this.props.popout) { hiddenClasses = false; } else { hiddenClasses = this.props.sidebarShown; } return ( <div className={`bn br-m br-l br-xl b--gray4 b--gray1-d lh-copy h-100 flex-shrink-0 mw5-m mw5-l mw5-xl pt3 pt0-m pt0-l pt0-xl relative ` + activeClasses + ((hiddenClasses) ? "flex-basis-100-s flex-basis-30-ns" : "dn")}> <a className="db dn-m dn-l dn-xl f8 pb3 pl3" href="/">⟵ Landscape</a> <div className="overflow-y-scroll h-100"> <div className="w-100 bg-transparent"> <Link className="dib f9 pointer green2 gray4-d pa4" to={"/~link/new"}> New Collection </Link> </div> <Welcome associations={props.associations}/> {sidebarInvites} {groupedItems} </div> </div> ); } }
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
boneyao/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
src/layouts/index.js
btthomas/blakeandanna
import React from 'react' import PropTypes from 'prop-types' import Link from 'gatsby-link' import Helmet from 'react-helmet' import pages from '../pageList.js' import Burger from './burger.js' import './index.css' const Header = () => <div id="top-bar" style={{ marginBottom: '1rem', }} > <div style={{ margin: '0 auto', maxWidth: 960, padding: '1rem 0.5rem', }} > <div style={{display: 'inline-block', width: '85%'}}> <h1 style={{ margin: 0 }}> <Link to="/" style={{ color: '#fff', textDecoration: 'none', }} > Blake <span id="heart">♥</span> Anna </Link> </h1> <h2 style={{ margin: 0 }}> February 3, 2018 </h2> </div> <Burger> <Link to="/">home</Link> {pages.map(page => <Link key={page} to={`/${page}/`}>{page}</Link>)} </Burger> </div> </div> const TemplateWrapper = ({ children }) => <div> <Helmet title="Blake and Anna - February 3, 2018" meta={[ { name: 'description', content: 'Blake and Anna are getting married on February 3rd, 2018' }, ]} /> <Header /> <div style={{ margin: '0 auto', maxWidth: 960, padding: '0px 1.0875rem 1.45rem', paddingTop: 0, }} > {children()} </div> </div> TemplateWrapper.propTypes = { children: PropTypes.func, } export default TemplateWrapper
frontend/src/components/common/hoc/withCountryName.js
unicef/un-partner-portal
// eslint-disable-next-line import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const withCountryName = ComposedComponent => connect( (state, ownProps) => ({ countryName: state.countries[ownProps.code], }), )(ComposedComponent); withCountryName.propTypes = { countryName: PropTypes.string.isRequired, }; export default withCountryName;
src/components/input-group/InputGroupPrepend.js
ProAI/react-essentials
import React from 'react'; import PropTypes from 'prop-types'; import BaseView from '../../utils/rnw-compat/BaseView'; const propTypes = { children: PropTypes.node.isRequired, }; const InputGroupPrepend = React.forwardRef((props, ref) => ( <BaseView {...props} ref={ref} essentials={{ className: 'input-group-prepend' }} /> )); InputGroupPrepend.displayName = 'InputGroupPrepend'; InputGroupPrepend.propTypes = propTypes; export default InputGroupPrepend;
src/components/article/slideshow/thumbnails.js
hanyulo/twreporter-react
/*eslint-disable no-console*/ 'use strict' import classNames from 'classnames' import styles from './thumbnails.scss' import React from 'react' // lodash import get from 'lodash/get' import map from 'lodash/map' const defaultThumbnailWidth = 56 const Thumbnail = (props) => { const { alt, customClassName, greyOut, onThumbError, onThumbLoad, src, slideToIndex, thumbnailWidth } = props const _onEvent = (event) => { console.log(event.target.src) } let onError = typeof onThumbError === 'function' ? onThumbError : _onEvent let onLoad = typeof onThumbLoad === 'function' ? onThumbLoad : _onEvent return ( <li className={classNames(customClassName, styles['thumbnail'], greyOut ? styles['grey-out'] : '')} onClick={slideToIndex} onTouchStart={slideToIndex} > <img alt={alt} src={src} onError={onError} onLoad={onLoad} style={{ width: thumbnailWidth, height: thumbnailWidth }} /> </li> ) } const Thumbnails = (props) => { let { customClassName, currentIndex, thumbnails, thumbnailOffset, thumbnailWidth, onThumbError, onThumbLoad, slideToIndex, width } = props thumbnailWidth = thumbnailWidth || defaultThumbnailWidth const _slideToIndex = (index, event) => { slideToIndex(index, event) } let thumbnailComponents = map(thumbnails, (thumbnail, index) => { return ( <Thumbnail alt={thumbnail.alt} customClassName={thumbnail.customClassName} greyOut={currentIndex === index ? false : true} key={thumbnail.id} onThumbLoad={onThumbLoad} onThumbError={onThumbError} slideToIndex={_slideToIndex.bind(null, index)} src={thumbnail.src} thumbnailWidth={thumbnailWidth} /> ) }) let length = get(thumbnails, 'length', 0) // calculate how many thumbnails can show in the thumbnails conatiner let maximum = Math.floor((width - thumbnailOffset * (length - 1))/ thumbnailWidth) let translateX if (maximum > currentIndex) { translateX = 'translateX(0px)' } else { // current thumbnail is not shown in the thumbnails container translateX = `translateX(${-(currentIndex + 1 - maximum) * thumbnailWidth - thumbnailOffset * 2 }px)` } let style = { WebkitTransform: translateX, MozTransform: translateX, msTransform: translateX, OTransform: translateX, transform: translateX } return ( <ul className={classNames(styles['thumbnails'], maximum > length ? styles['flex-center'] : '',customClassName)} style={style}> {thumbnailComponents} </ul> ) } export default Thumbnails
frontend/src/Album/Search/AlbumInteractiveSearchModal.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import AlbumInteractiveSearchModalContent from './AlbumInteractiveSearchModalContent'; function AlbumInteractiveSearchModal(props) { const { isOpen, albumId, albumTitle, onModalClose } = props; return ( <Modal isOpen={isOpen} closeOnBackgroundClick={false} onModalClose={onModalClose} > <AlbumInteractiveSearchModalContent albumId={albumId} albumTitle={albumTitle} onModalClose={onModalClose} /> </Modal> ); } AlbumInteractiveSearchModal.propTypes = { isOpen: PropTypes.bool.isRequired, albumId: PropTypes.number.isRequired, albumTitle: PropTypes.string.isRequired, onModalClose: PropTypes.func.isRequired }; export default AlbumInteractiveSearchModal;
src/js/templates/index.js
julianburr/wp-react-theme
import React, { Component } from 'react'; import Header from '../components/header'; import Footer from '../components/footer'; import 'styles/index.scss'; export default class Index extends Component { render () { return ( <div className="wrap-all"> <Header /> <div className="content"> <div className="inner"> {this.props.children} </div> </div> <Footer /> </div> ); } }
src/svg-icons/device/screen-rotation.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenRotation = (props) => ( <SvgIcon {...props}> <path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/> </SvgIcon> ); DeviceScreenRotation = pure(DeviceScreenRotation); DeviceScreenRotation.displayName = 'DeviceScreenRotation'; DeviceScreenRotation.muiName = 'SvgIcon'; export default DeviceScreenRotation;
src/common/components/Button.js
sikhote/davidsinclair
// @flow import type { ColorProps, Theme } from '../themes/types'; import type { TextProps } from './Text'; import Box from './Box'; import React from 'react'; import Text, { computeTextStyle } from './Text'; import isReactNative from '../../common/app/isReactNative'; export type ButtonProps = ColorProps & TextProps & { // For blindness accessibility features. Consider making it mandatory. accessibilityLabel?: string, boxStyle?: (theme: Theme) => Object, children?: any, disabled?: boolean, onPress?: (e?: SyntheticMouseEvent) => any, outline?: boolean, textStyle?: (theme: Theme) => Object, }; type ButtonContext = { Button: () => React.Element<*>, theme: Theme, }; const Button = ({ as, accessibilityLabel, boxStyle, children, disabled, onPress, outline, textStyle, ...props }: ButtonProps, { Button: PlatformButton, theme, }: ButtonContext) => { const platformProps = isReactNative ? { accessibilityComponentType: 'button', accessibilityLabel, accessibilityTraits: ['button'], activeOpacity: theme.states.active.opacity, onPress, } : { onClick: onPress, }; const colorProps = Object.keys(theme.colors); // <Button primary // any is needed probably because Array find is not yet fully typed. const propColor: any = colorProps.find(color => props[color]); if (propColor) { props = { ...props, backgroundColor: propColor, bold: true, color: 'white', paddingHorizontal: 1, }; } // <Button primary outline if (propColor && outline) { delete props.backgroundColor; props = { ...props, bold: false, borderColor: props.backgroundColor, borderStyle: 'solid', borderWidth: 1, color: props.backgroundColor, paddingHorizontal: 1, }; } // Give button some vertical space. const { size = 0 } = props; if (size >= 0) { props = { marginVertical: 0.3, paddingVertical: 0.2, ...props, }; } else { props = { marginVertical: 0.5, ...props, }; if (props.borderWidth) { props = { // Ensure vertical Rhythm for Button size < 0. The lineHeight is the // only possible way how to do it. It doesn't work for multilines lineHeight: theme.typography.lineHeight - (2 * props.borderWidth), ...props, }; } } // Button consists of two components, Box and Text. That's because Button can // render not only text, but any component, and React Native Text can't // contain View based components. // Therefore, we have to split props for Box and props for Text. Fortunately, // that's what computeTextStyle does by design. It picks own props and return // the rest. We can also use boxStyle and textStyle props for further styling. const [computedTextStyle, allBoxProps] = computeTextStyle(theme, props); // To prevent "Unknown prop" warning, we have to remove color props. const boxProps = colorProps.reduce((props, prop) => { delete props[prop]; return props; }, allBoxProps); const childrenIsText = typeof children === 'string'; const { borderRadius = theme.button.borderRadius, } = props; return ( <Box as={as || PlatformButton} borderRadius={borderRadius} disabled={disabled} // Do we need that? flexDirection="row" justifyContent="center" opacity={disabled ? theme.states.disabled.opacity : 1} {...platformProps} {...boxProps} style={boxStyle} > {childrenIsText ? <Text // Pass backgroundColor to Text for maybeFixFontSmoothing function. backgroundColor={props.backgroundColor} style={theme => ({ ...computedTextStyle, ...(textStyle && textStyle(theme, computedTextStyle)), })} >{children}</Text> : children } </Box> ); }; Button.contextTypes = { Button: React.PropTypes.func, theme: React.PropTypes.object, }; export default Button;
examples/animations/app.js
mattydoincode/react-router
import React from 'react' import { render } from 'react-dom' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import StaticContainer from 'react-static-container' import { createHistory, useBasename } from 'history' import { Router, Route, Link } from 'react-router' require('./app.css') const history = useBasename(createHistory)({ basename: '/animations' }) /** * <RouteCSSTransitionGroup> renders twice on a route change. On the first * render, it "freezes" the transitioning-out component by setting * `shouldUpdate` on the <StaticContainer> to `false`. This prevents any * <Link>s nested under the old component from updating their active state to * reflect the new location, to allow for a smooth transition out. It then * renders the new, transitioning-in component immediately afterward. */ class RouteCSSTransitionGroup extends React.Component { constructor(props, context) { super(props, context) this.state = { previousPathname: null } } componentWillReceiveProps(nextProps, nextContext) { if (nextContext.location.pathname !== this.context.location.pathname) { this.setState({ previousPathname: this.context.location.pathname }) } } render() { const { children, ...props } = this.props const { previousPathname } = this.state return ( <ReactCSSTransitionGroup {...props}> <StaticContainer key={previousPathname || this.context.location.pathname} shouldUpdate={!previousPathname} > {children} </StaticContainer> </ReactCSSTransitionGroup> ) } componentDidUpdate() { if (this.state.previousPathname) { this.setState({ previousPathname: null }) } } } RouteCSSTransitionGroup.contextTypes = { location: React.PropTypes.object } class App extends React.Component { render() { return ( <div> <ul> <li><Link to="/page1">Page 1</Link></li> <li><Link to="/page2">Page 2</Link></li> </ul> <RouteCSSTransitionGroup component="div" transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500} > {this.props.children} </RouteCSSTransitionGroup> </div> ) } } class Page1 extends React.Component { render() { return ( <div className="Image"> <h1>Page 1</h1> <p><Link to="/page1" activeClassName="link-active">A link to page 1 should be active</Link>. Lorem ipsum dolor sit amet, consectetur adipisicing elit. <Link to="/page2" activeClassName="link-active">A link to page 2 should be inactive</Link>. Do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) } } class Page2 extends React.Component { render() { return ( <div className="Image"> <h1>Page 2</h1> <p>Consectetur adipisicing elit, sed do <Link to="/page2" activeClassName="link-active">a link to page 2 should also be active</Link> eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) } } render(( <Router history={history}> <Route path="/" component={App}> <Route path="page1" component={Page1} /> <Route path="page2" component={Page2} /> </Route> </Router> ), document.getElementById('example'))
src/parser/shared/modules/earlydotrefreshes/EarlyDotRefreshesSuggestionByCount.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import { SpellLink } from 'interface'; import React from 'react'; function suggest(when, suggestion) { when(suggestion).addSuggestion((suggest, actual, recommended) => suggest( <> You refreshed <SpellLink id={suggestion.spell.id} /> early {suggestion.count} times. The individual casts are highlighted on the timeline. </>, ) .icon(suggestion.spell.icon) .actual( t({ id: 'shared.suggestions.dots.countEarlyRefreshes', message: `${formatPercentage(actual)}% effective duration`, }), ) .recommended(`<${formatPercentage(recommended)}% is recommended`), ); } export default suggest;
src/components/Weather/Weather.js
andresol/sollieweb
import React from 'react' import { Link } from 'react-router' export class Weather extends React.Component { getTitle () { return this.title } getValue () { return this.name } render () { return ( <div> <h2>{this.getTitle()}</h2> <div className='live wind'>{this.getValue()}</div> <p> <Link /> </p> </div> ) } } Weather.defaultProps = { title: '' } Weather.propTypes = { getWeather: React.PropTypes.func, title: React.PropTypes.string, value: React.PropTypes.string } export class Wind extends Weather { constructor (props) { super(props) this.title = props.weather.name this.value = '' const { updateWind } = props.updateWind() if (updateWind) { updateWind() } } } // data[0].value Wind.defaultProps = { weather: { name: '', data: {} }, updateWind: () => '' } export class Temp extends Weather { constructor (props) { super(props) this.title = props.weather.name this.value = '' const { updateWind } = props.updateTemp() if (updateWind) { updateWind() } } } Temp.defaultProps = { weather: { name: '', data: [] }, updateTemp: () => '' }
assets/js/app.js
ChrisBr/duell-um-die-geld
import React from 'react'; import ReactDOM from 'react-dom'; import GameContainer from './react/gameContainer' window.jQuery = window.$ = require('../bower_components/jquery/dist/jquery.min.js'); //import bootstrapJs from '../bower_components/bootstrap/dist/js/bootstrap.min.js'; import bootstrapStyles from '../bower_components/bootstrap/dist/css/bootstrap.min.css'; $(function whenDomIsReady() { // as soon as this file is loaded, connect automatically, //var socket = io.sails.connect(); //window.socket = socket; ReactDOM.render( <GameContainer />, document.getElementById('root') ); });
imports/ui/components/header/header-notifications.js
irvinlim/free4all
import React from 'react'; import { browserHistory } from 'react-router'; import * as Colors from 'material-ui/styles/colors'; import Badge from 'material-ui/Badge'; import IconButton from 'material-ui/IconButton'; import Popover from 'material-ui/Popover'; import NotificationsList from './notifications-list'; import * as IconsHelper from '../../../util/icons'; export class HeaderNotifications extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } handleOnTouchTap(event) { event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); } handleRequestClose() { this.setState({ open: false }); } handleNotificationTouchTap(id, url) { const self = this; return function(event) { // Prevent ghost clicks event.preventDefault(); // Close the popover self.setState({ open: false }) // Set as read Herald.collection.update(id, { $set: { read: true } }); // Follow link if (url && url.length) { if (url.charAt(0) == "/") browserHistory.push(url); else window.location = url; } } } render() { if (!Meteor.user()) return <div />; else return ( <div id="header-notifications"> <Badge style={{ padding:0 }} badgeStyle={{ height: 20, width: 20, backgroundColor: 'rgba(255, 255, 255, 0.65)', color:'#045d68' }} badgeContent={ this.props.notificationCount }> <IconButton onTouchTap={ this.handleOnTouchTap.bind(this) } children={ IconsHelper.icon("notifications", { color: Colors.grey50 }) } /> </Badge> <Popover open={ this.state.open } anchorEl={ this.state.anchorEl } onRequestClose={ this.handleRequestClose.bind(this) } anchorOrigin={{"horizontal":"right","vertical":"bottom"}} targetOrigin={{"horizontal":"right","vertical":"top"}} style={{ maxWidth: 500, width: "calc(100% - 20px)", marginLeft: 10 }}> <NotificationsList notifications={ this.props.notifications } handleNotificationTouchTap={ this.handleNotificationTouchTap.bind(this) } /> </Popover> </div> ); } }
wisewit_front_end/public/js/userAuth/user_controller.js
emineKoc/WiseWit
'use strict' import React from 'react'; import SessionStore from './session_store.js'; import AuthActions from './auth_actions.js'; let UserControls = React.createClass({ handleLogout(e) { e.preventDefault(); AuthActions.logout(); }, render() { if (SessionStore.isLoggedIn()) { return ( <div className='UserControls'> <span>{SessionStore.getemail}</span> <a href='#' onClick={this.handleLogout}>Logout</span> </div> ); } else { return ( <div className='UserControls'> <a href='#/login'>Login</a> </div> ); } } }); export default UserControls;
src/svg-icons/image/camera-front.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraFront = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/> </SvgIcon> ); ImageCameraFront = pure(ImageCameraFront); ImageCameraFront.displayName = 'ImageCameraFront'; ImageCameraFront.muiName = 'SvgIcon'; export default ImageCameraFront;
imports/ui/components/Navigation/Navigation.js
jamiebones/Journal_Publication
import React from 'react'; import PropTypes from 'prop-types'; import { Navbar , Nav, NavItem } from 'react-bootstrap'; import { Link } from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; import Icon from '../../components/Icon/Icon'; import PublicNavigation from '../PublicNavigation/PublicNavigation'; import AuthenticatedNavigation from '../AuthenticatedNavigation/AuthenticatedNavigation'; import './Navigation.scss'; const Navigation = props => ( <div className="appNav"> <Navbar fluid> <Navbar.Header> <Navbar.Brand> <Link to="" className="navbar-brand"> <img src="/image/elogo.png" alt="Erudite Scholars"/> </Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <LinkContainer exact to="/"> <NavItem href="/">Home</NavItem> </LinkContainer> </Nav> <Nav> <LinkContainer to="/search_published_paper"> <NavItem eventKey={2} href="/search_published_paper">Search For Papers</NavItem> </LinkContainer> </Nav> <PublicNavigation {...props} /> </Navbar.Collapse> </Navbar> </div> ); Navigation.defaultProps = { name: '', }; Navigation.propTypes = { authenticated: PropTypes.bool.isRequired, }; export default Navigation;
styleguide.js
mazzcris/sortello
import {render} from 'react-dom' import React from 'react' import StyleguideApp from './StyleguideApp.jsx' import Bootstrap from 'bootstrap/dist/css/bootstrap.min.css' import "./css/style.css"; import "./css/animate-sortello.css"; import "./css/buttons.css"; import "./css/api-key.css"; import "./css/board-column__selection.css"; import "./css/choices.css"; import "./css/responsive/board-column-selection__responsive.css"; import "./css/responsive/choices__responsive.css"; import "./css/logout-button.css"; import "./css/responsive/logout-button__responsive.css"; import "./css/footer.css"; import "./css/responsive/footer__responsive.css"; import "./css/responsive/api-key__responsive.css"; import "./css/responsive/disclaimer__responsive.css"; import "./css/disclaimer.css"; import "./css/send-ordered.css"; import "./css/send-success.css"; import "./css/responsive/send-success__responsive.css"; import "./css/responsive/send-ordered__responsive.css"; import "./css/recap.css"; import "./css/responsive/recap__responsive.css"; import "./css/prioritization-end.css"; import "./css/responsive/prioritization-end__responsive.css"; import "./css/no-access-message.css"; const containerEl = document.getElementById("container") render(<StyleguideApp/>, containerEl)
docs/src/examples/elements/Reveal/States/RevealExampleDisabled.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Image, Reveal } from 'semantic-ui-react' const RevealExampleDisabled = () => ( <Reveal animated='move' disabled> <Reveal.Content visible> <Image src='/images/wireframe/square-image.png' size='small' /> </Reveal.Content> <Reveal.Content hidden> <Image src='/images/avatar/large/chris.jpg' size='small' /> </Reveal.Content> </Reveal> ) export default RevealExampleDisabled
modules/useRouterRestoreScroll.js
jshin49/react-router-restore-scroll
import React from 'react' import RestoreWindowScroll from './RestoreWindowScroll' const useRouterRestoreScroll = () => ({ renderRouterContext: (child, props) => ( <RestoreWindowScroll restoreWindow={props.router.restoreScroll.restoreWindow} location={props.location} children={child} /> ) }) export default useRouterRestoreScroll
examples/real-world/index.js
nickhudkins/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; import BrowserHistory from 'react-router/lib/BrowserHistory'; React.render( <Root history={new BrowserHistory()} />, document.getElementById('root') );
app/components/PointList/index.js
GuiaLa/guiala-web-app
/** * * PointList * */ import React from 'react'; import PointListItem from 'PointListItem' import styles from './styles.css'; class PointList extends React.Component { render() { const { items, params } = this.props; return ( <div className={ styles.wrapper }> { items.map((item, key) => <PointListItem key={key} {...item} place={params.placeSlug} /> )} </div> ); } } export default PointList;
tests/react_native_tests/test_data/native_code/ToolbarAndroid/app/components/Mobile/index.js
ibhubs/sketch-components
/** * @flow */ import React from 'react' import PropTypes from 'prop-types' import { observer } from 'mobx-react/native' import styles from './styles' import Mobile from './component' @observer class MobileWrapper extends React.Component { render() { return ( <Mobile {...this.props} ></Mobile> ); } } export default MobileWrapper
src/rodal.js
chenjiahan/rodal
/* =============================== * Rodal v1.8.2 https://chenjiahan.github.com/rodal * =============================== */ import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; // env const IN_BROWSER = typeof window !== 'undefined'; const UA = IN_BROWSER && window.navigator.userAgent.toLowerCase(); const IS_IE_9 = UA && UA.indexOf('msie 9.0') > 0; const Dialog = props => { const animation = (props.animationType === 'enter' ? props.enterAnimation : props.leaveAnimation) || props.animation; const className = `rodal-dialog rodal-${animation}-${props.animationType}`; const CloseButton = props.showCloseButton ? ( <span className="rodal-close" onClick={props.onClose} onKeyPress={event => { if (props.onClose && event.which === 13) { props.onClose(event); } }} tabIndex={0} /> ) : null; const { width, height, measure, duration, customStyles, id } = props; const style = { width: width + measure, height: height + measure, animationDuration: duration + 'ms', WebkitAnimationDuration: duration + 'ms' }; const mergedStyles = { ...style, ...customStyles }; return ( <div style={mergedStyles} className={className} id={id}> {props.children} {CloseButton} </div> ); }; class Rodal extends React.Component { static propTypes = { width: PropTypes.number, height: PropTypes.number, measure: PropTypes.string, visible: PropTypes.bool, showMask: PropTypes.bool, closeOnEsc: PropTypes.bool, closeMaskOnClick: PropTypes.bool, showCloseButton: PropTypes.bool, animation: PropTypes.string, enterAnimation: PropTypes.string, leaveAnimation: PropTypes.string, duration: PropTypes.number, className: PropTypes.string, customStyles: PropTypes.object, customMaskStyles: PropTypes.object, onClose: PropTypes.func.isRequired, onAnimationEnd: PropTypes.func, id:PropTypes.string }; static defaultProps = { width: 400, height: 240, measure: 'px', visible: false, showMask: true, closeOnEsc: false, closeMaskOnClick: true, showCloseButton: true, animation: 'zoom', enterAnimation: '', leaveAnimation: '', duration: 300, className: '', customStyles: {}, customMaskStyles: {} }; state = { isShow: false, animationType: 'leave' }; componentDidMount() { if (this.props.visible) { this.enter(); } } componentDidUpdate(prevProps) { if (this.props.visible && !prevProps.visible) { this.enter(); } if (!this.props.visible && prevProps.visible) { this.leave(); } } enter() { this.setState({ isShow: true, animationType: 'enter' }); } leave() { this.setState(IS_IE_9 ? { isShow: false } : { animationType: 'leave' }); } onKeyUp = event => { if (!this.props.closeOnEsc || event.keyCode !== 27) { return; } this.props.onClose(event); }; animationEnd = event => { const { animationType } = this.state; const { closeOnEsc, onAnimationEnd } = this.props; if (animationType === 'leave') { this.setState({ isShow: false }); } else if (closeOnEsc) { this.el.focus(); } if (event.target === this.el && onAnimationEnd) { onAnimationEnd(); } }; render() { const { closeMaskOnClick, onClose, customMaskStyles, showMask, duration, className, children } = this.props; const { isShow, animationType } = this.state; const Mask = showMask ? ( <div className="rodal-mask" style={customMaskStyles} onClick={closeMaskOnClick ? onClose : void 0} /> ) : null; const style = { display: isShow ? '' : 'none', animationDuration: duration + 'ms', WebkitAnimationDuration: duration + 'ms' }; return ( <div style={style} className={cx('rodal', `rodal-fade-${animationType}`, className)} onAnimationEnd={this.animationEnd} tabIndex="-1" ref={el => { this.el = el; }} onKeyUp={this.onKeyUp} > {Mask} <Dialog {...this.props} animationType={animationType}> {children} </Dialog> </div> ); } } export default Rodal;
notebook/experience/web/webpack4-upgrade-log/simple-webpack-config/src/components/confirm.js
JMwill/wiki
import React from 'react' import modal from './modal' /** * 弹出确认窗 * @param {[type]} options.message 消息 * @param {[type]} options.ok 确认的回调函数 * @param {String} okLabel 确认按钮标签 * @param {[type]} cancel 取消的回调函数 * @param {String} cancelLabel 取消按钮标签 * @return {[type]} 销毁函数 */ function withConfirm({ message, ok = function() { }, okLabel = '确定', cancel = function() {}, cancelLabel = '取消', }) { return function({close}) { return ( <div className='pepe-modal-table'> <div className='bd'>{message}</div> <div className='ft'> <button className='btn btn-primary' onClick={() => { ok() close() }} > {okLabel} </button> <button className='btn btn-default' onClick={() => { cancel() close() }} > {cancelLabel} </button> </div> </div> ) } } export default function confirm(props) { return modal({ component: withConfirm(props), header: (props.title != null), title: props.title, size: 'sm', }) }
src/routes/register/index.js
rameshrr/dicomviewer
/** * 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 Layout from '../../components/Layout'; import Register from './Register'; const title = 'New User Registration'; function action() { return { chunks: ['register'], title, component: ( <Layout> <Register title={title} /> </Layout> ), }; } export default action;
tom-binary-tree/src/Button.js
slorber/scalable-frontend-with-elm-or-redux
import React from 'react' // EVENTS class Toggle { update(model) { return { model: !model } } } // APP export default { init() { return { model: true } }, update(model, event) { return event.update(model) }, view(model, dispatch) { const onClick = () => dispatch(new Toggle()) const style = { backgroundColor: model ? 'green' : 'red' } return <button onClick={onClick} style={style}>Click</button> } }
react/features/device-selection/components/DeviceSelector.js
parisjulien/arkadin-jitsimeet
import AKDropdownMenu from '@atlaskit/dropdown-menu'; import ExpandIcon from '@atlaskit/icon/glyph/expand'; import React, { Component } from 'react'; import { translate } from '../../base/i18n'; const EXPAND_ICON = <ExpandIcon label = 'expand' />; /** * React component for selecting a device from a select element. Wraps * AKDropdownMenu with device selection specific logic. * * @extends Component */ class DeviceSelector extends Component { /** * DeviceSelector component's property types. * * @static */ static propTypes = { /** * MediaDeviceInfos used for display in the select element. */ devices: React.PropTypes.array, /** * If false, will return a selector with no selection options. */ hasPermission: React.PropTypes.bool, /** * CSS class for the icon to the left of the dropdown trigger. */ icon: React.PropTypes.string, /** * If true, will render the selector disabled with a default selection. */ isDisabled: React.PropTypes.bool, /** * The translation key to display as a menu label. */ label: React.PropTypes.string, /** * The callback to invoke when a selection is made. */ onSelect: React.PropTypes.func, /** * The default device to display as selected. */ selectedDeviceId: React.PropTypes.string, /** * Invoked to obtain translated strings. */ t: React.PropTypes.func }; /** * Initializes a new DeviceSelector instance. * * @param {Object} props - The read-only React Component props with which * the new instance is to be initialized. */ constructor(props) { super(props); this._onSelect = this._onSelect.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { if (!this.props.hasPermission) { return this._renderNoPermission(); } if (!this.props.devices.length) { return this._renderNoDevices(); } const items = this.props.devices.map(this._createDropdownItem); const defaultSelected = items.find(item => item.value === this.props.selectedDeviceId ); return this._createDropdown({ defaultSelected, isDisabled: this.props.isDisabled, items, placeholder: this.props.t('deviceSelection.selectADevice') }); } /** * Creates a React Element for displaying the passed in text surrounded by * two icons. The left icon is the icon class passed in through props and * the right icon is AtlasKit ExpandIcon. * * @param {string} triggerText - The text to display within the element. * @private * @returns {ReactElement} */ _createDropdownTrigger(triggerText) { return ( <div className = 'device-selector-trigger'> <span className = { `device-selector-icon ${this.props.icon}` } /> <span className = 'device-selector-trigger-text'> { triggerText } </span> { EXPAND_ICON } </div> ); } /** * Creates an object in the format expected by AKDropdownMenu for an option. * * @param {MediaDeviceInfo} device - An object with a label and a deviceId. * @private * @returns {Object} The passed in media device description converted to a * format recognized as a valid AKDropdownMenu item. */ _createDropdownItem(device) { return { content: device.label, value: device.deviceId }; } /** * Creates a AKDropdownMenu Component using passed in props and options. If * the dropdown needs to be disabled, then only the AKDropdownMenu trigger * element is returned to simulate a disabled state. * * @param {Object} options - Additional configuration for display. * @param {Object} options.defaultSelected - The option that should be set * as currently chosen. * @param {boolean} options.isDisabled - If true, only the AKDropdownMenu * trigger component will be returned to simulate a disabled dropdown. * @param {Array} options.items - All the selectable options to display. * @param {string} options.placeholder - The translation key to display when * no selection has been made. * @private * @returns {ReactElement} */ _createDropdown(options) { const triggerText = (options.defaultSelected && options.defaultSelected.content) || options.placeholder; const trigger = this._createDropdownTrigger(triggerText); if (options.isDisabled) { return ( <div className = 'device-selector-trigger-disabled'> { trigger } </div> ); } return ( <AKDropdownMenu items = { [ { items: options.items || [] } ] } onItemActivated = { this._onSelect } shouldFitContainer = { true }> { trigger } </AKDropdownMenu> ); } /** * Invokes the passed in callback to notify of selection changes. * * @param {Object} selection - Event from choosing a AKDropdownMenu option. * @private * @returns {void} */ _onSelect(selection) { const newDeviceId = selection.item.value; if (this.props.selectedDeviceId !== newDeviceId) { this.props.onSelect(selection.item.value); } } /** * Creates a Select Component that is disabled and has a placeholder * indicating there are no devices to select. * * @private * @returns {ReactElement} */ _renderNoDevices() { return this._createDropdown({ isDisabled: true, placeholder: this.props.t('settings.noDevice') }); } /** * Creates a AKDropdownMenu Component that is disabled and has a placeholder * stating there is no permission to display the devices. * * @private * @returns {ReactElement} */ _renderNoPermission() { return this._createDropdown({ isDisabled: true, placeholder: this.props.t('deviceSelection.noPermission') }); } } export default translate(DeviceSelector);
src/packages/recompose/__tests__/types/test_withStateHandlers.js
acdlite/recompose
/* eslint-disable no-unused-vars, no-unused-expressions */ /* @flow */ import React from 'react' import { compose, withProps, withStateHandlers } from '../..' import type { HOC } from '../..' type EnhancedCompProps = { initialCounter: number, } const enhancer: HOC<*, EnhancedCompProps> = compose( withStateHandlers( { value: 'Hello', letIt: 'be', obj: ({}: { [key: string]: string }) }, { // we need to set argument type so inference will work good setValue: (state, props) => (value: string) => ({ value, }), changeValue: (state, props) => ( { i, j }: { i: number, j: string }, k: number ) => ({ value: `world again ${i} ${j}`, }), inform: state => () => {}, } ), // here props itself will not be infered without explicit handler args types withProps(props => ({ hi: (props.value: string), ic: (props.initialCounter: number), cc: (props.obj.a: string), // $ExpectError value not a number or any ehi: (props.value: number), // $ExpectError not a number cn: (props.obj.a: number), // $ExpectError property not found (to detect that props is not any) err: props.iMNotExists, // $ExpectError initialCounter not any nor string icErr: (props.initialCounter: string), })) ) const enhancerFuncInit: HOC<*, EnhancedCompProps> = compose( withStateHandlers( props => ({ counter: props.initialCounter, }), { // it's better to set argument type with named props, easier to find an error // if you call it with wrong arguments incCounter: ({ counter }) => ({ value }: { value: number }) => ({ counter: counter + value, }), } ), withProps(props => ({ // check that result is void iVal: (props.incCounter({ value: 1 }): void), // $ExpectError check that incCounter is not any iVal2: (props.incCounter({ value: 1 }): number), // $ExpectError property not found err: props.iMNotExists, })) ) const BaseComponent = ({ hi, changeValue, setValue }) => <div onClick={() => { // check that supports few arguments const x = changeValue({ i: 1, j: '1' }, 1) setValue('ww') // Check that result is void ;(x: void) // $ExpectError check that x is not any ;(x: {}) // Check hi ;(hi: string) // $ExpectError check that hi is not any ;(hi: number) }} > {hi} </div> const EnhancedComponent = enhancer(BaseComponent) ;<EnhancedComponent initialCounter={0} /> // Without $Exact<State> this will cause error const enhancer3: HOC<*, EnhancedCompProps> = compose( withStateHandlers( ({ mapA2B: {}, }: { mapA2B: { [key: string]: string } }), {} ), withProps(props => ({ // check that result is void iVal: props.mapA2B.c, })) )
src/components/TopNav.js
one-stop-team/ripta-app
import React from 'react' import * as bs from 'react-bootstrap' import logo from '../images/ripta_logo.png' const LinkContainer = ({children}) => ( <span>{children}</span> ) export default class TopNav extends React.Component { render() { return ( <bs.Navbar fixedTop fluid> <bs.Navbar.Header> <bs.Navbar.Brand> <img src={logo} alt="RIPTA" /> </bs.Navbar.Brand> <bs.Navbar.Toggle /> </bs.Navbar.Header> <bs.Navbar.Collapse> <bs.Nav> <bs.NavItem>Home</bs.NavItem> <bs.NavItem>Schedules</bs.NavItem> <bs.NavItem>Alerts</bs.NavItem> </bs.Nav> </bs.Navbar.Collapse> </bs.Navbar> ) } }
src/modules/Hemmo.js
futurice/PelaryHemmo
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { StyleSheet, Modal, AppState, Text, View, Platform, TouchableOpacity, } from 'react-native'; import { getSizeByWidth, getFontSize } from '../services/graphics'; import AudioPlayerViewContainer from './AudioPlayerViewContainer'; import { toggleMute, setText, setAudio } from '../state/HemmoState'; import AppButton from '../components/AppButton'; const styles = StyleSheet.create({ container: { position: 'absolute', right: 0, }, hemmo: { alignSelf: 'flex-end', right: getFontSize(1), top: getFontSize(1.5), ...Platform.select({ ios: { top: getFontSize(2.8), }, }), }, bubbleContainer: { flex: 1, flexDirection: 'column', zIndex: 10000, backgroundColor: 'rgba(255,255,255,0.8)', alignItems: 'center', }, bubble: { position: 'absolute', top: getFontSize(4), right: getFontSize(5), marginTop: getFontSize(5), }, toggleVolumeButton: { position: 'absolute', left: 0, bottom: 0, padding: getFontSize(2), }, text: { padding: 70, textAlign: 'center', alignSelf: 'center', fontSize: getFontSize(1.8), color: '#000', fontFamily: 'ComicNeue-Bold', }, }); const phrases = require('../data/phrases.json'); const mapStateToProps = state => ({ text: state.getIn(['hemmo', 'text']), audio: state.getIn(['hemmo', 'audio']), muted: state.getIn(['hemmo', 'muted']), activeRoute: state.getIn([ 'navigatorState', 'routes', state.getIn(['navigatorState', 'index']), 'routeName', ]), routes: state.getIn(['navigatorState', 'routes']), }); const mapDispatchToProps = dispatch => ({ toggleMute: () => dispatch(toggleMute()), setText: text => dispatch(setText(text)), setAudio: audio => dispatch(setAudio(audio)), }); @connect(mapStateToProps, mapDispatchToProps) export default class Hemmo extends Component { static propTypes = { activeRoute: PropTypes.string.isRequired, text: PropTypes.string.isRequired, audio: PropTypes.string.isRequired, setText: PropTypes.func.isRequired, setAudio: PropTypes.func.isRequired, toggleMute: PropTypes.func.isRequired, muted: PropTypes.bool.isRequired, }; state = { currentAppState: AppState.currentState, showBubble: false, mutePressed: false, }; componentDidMount() { AppState.addEventListener('change', this.handleAppStateChange); } async componentDidUpdate(prevProps) { if ( prevProps.activeRoute !== this.props.activeRoute && this.props.routes.size > prevProps.routes.size ) { if (this.props.activeRoute === 'Ending') { setTimeout(this.showBubble, 3000); } else { await this.showBubble(); } } if (this.props.routes.size < prevProps.routes.size) { await this.setEmptyText(); } } componentWillUnmount() { AppState.removeEventListener('change', this.handleAppStateChange); } onEnd = () => { setTimeout(this.hideBubble, 500); }; setDefaultText = async () => { const routeName = this.props.activeRoute; if (!phrases[routeName]) return; await this.props.setText(phrases[routeName].text); await this.props.setAudio(phrases[routeName].audio); }; setEmptyText = async () => { await this.props.setText(''); await this.props.setAudio(''); }; showBubble = async () => { if (!this.props.text || !this.props.audio) { await this.setDefaultText(); } if ( this.state.currentAppState === 'active' && this.props.text && this.props.audio ) { this.setState({ showBubble: true }); } }; hideBubble = async () => { this.setState({ showBubble: false, mutePressed: false }); await this.setEmptyText(); }; toggleMute = async () => { if (this.props.muted) { await this.props.setAudio(phrases.unmute.audio); await this.props.setText(phrases.unmute.text); } else { this.setState({ mutePressed: true }); await this.props.setAudio(phrases.mute.audio); await this.props.setText(phrases.mute.text); } await this.props.toggleMute(); }; handleAppStateChange = async currentAppState => { if (currentAppState !== 'active') { await this.hideBubble(); } this.setState({ currentAppState }); }; renderBubble = () => this.state.showBubble ? <Modal animationType={'fade'} transparent visible={this.state.showBubble} onRequestClose={this.hideBubble} supportedOrientations={['portrait', 'landscape']} > <TouchableOpacity style={styles.bubbleContainer} onPress={this.hideBubble} > {this.renderHemmoButton()} {this.renderBubbleButton()} {this.renderMuteButton()} </TouchableOpacity> </Modal> : null; renderAudio = () => { if ( this.state.currentAppState === 'active' && this.props.audio && (!this.props.muted || this.state.mutePressed) ) { return ( <AudioPlayerViewContainer onEnd={this.onEnd} audioTrack={this.props.audio} /> ); } return null; }; renderMuteButton = () => <View style={styles.toggleVolumeButton}> <AppButton background={this.props.muted ? 'volume_is_off' : 'volume_is_on'} onPress={this.toggleMute} width={getSizeByWidth('volume_is_off', 0.23).width} shadow /> </View>; renderBubbleButton = () => <View style={styles.bubble}> <AppButton background="up_big" onPress={this.hideBubble} width={getSizeByWidth('up_big', 0.8).width} shadow > <Text style={styles.text}> {this.props.text} </Text> </AppButton> </View>; renderHemmoButton = () => <View style={styles.hemmo}> <AppButton background="hemmo" onPress={this.state.showBubble ? this.hideBubble : this.showBubble} width={getSizeByWidth('hemmo', 0.12).width} shadow /> </View>; render() { if ( this.props.activeRoute === 'Login' || this.props.activeRoute === 'Settings' ) { return null; } return ( <View style={styles.container}> {this.renderBubble()} {this.renderAudio()} {phrases[this.props.activeRoute] ? this.renderHemmoButton() : null} </View> ); } }
examples/with-clerk/pages/index.js
azukaru/next.js
import React from 'react' import Head from 'next/head' import Link from 'next/link' import styles from '../styles/Home.module.css' import { SignedIn, SignedOut } from '@clerk/nextjs' const ClerkFeatures = () => ( <Link href="/user"> <a className={styles.cardContent}> <img src="/icons/layout.svg" /> <div> <h3>Explore features provided by Clerk</h3> <p> Interact with the user button, user profile, and more to preview what your users will see </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const SignupLink = () => ( <Link href="/sign-up"> <a className={styles.cardContent}> <img src="/icons/user-plus.svg" /> <div> <h3>Sign up for an account</h3> <p> Sign up and sign in to explore all the features provided by Clerk out-of-the-box </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> ) const apiSample = `import { withSession } from '@clerk/nextjs/api' export default withSession((req, res) => { res.statusCode = 200 if (req.session) { res.json({ id: req.session.userId }) } else { res.json({ id: null }) } })` // Main component using <SignedIn> & <SignedOut>. // // The SignedIn and SignedOut components are used to control rendering depending // on whether or not a visitor is signed in. // // https://docs.clerk.dev/frontend/react/signedin-and-signedout const Main = () => ( <main className={styles.main}> <h1 className={styles.title}>Welcome to your new app</h1> <p className={styles.description}>Sign up for an account to get started</p> <div className={styles.cards}> <div className={styles.card}> <SignedIn> <ClerkFeatures /> </SignedIn> <SignedOut> <SignupLink /> </SignedOut> </div> <div className={styles.card}> <Link href="https://dashboard.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.cardContent}> <img src="/icons/settings.svg" /> <div> <h3>Configure settings for your app</h3> <p> Visit Clerk to manage instances and configure settings for user management, theme, and more </p> </div> <div className={styles.arrow}> <img src="/icons/arrow-right.svg" /> </div> </a> </Link> </div> </div> <APIRequest /> <div className={styles.links}> <Link href="https://docs.clerk.dev"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read Clerk documentation</span> </a> </Link> <Link href="https://nextjs.org/docs"> <a target="_blank" rel="noreferrer" className={styles.link}> <span className={styles.linkText}>Read NextJS documentation</span> </a> </Link> </div> </main> ) const APIRequest = () => { React.useEffect(() => { if (window.Prism) { window.Prism.highlightAll() } }) const [response, setResponse] = React.useState( '// Click above to run the request' ) const makeRequest = async () => { setResponse('// Loading...') try { const res = await fetch('/api/getAuthenticatedUserId') const body = await res.json() setResponse(JSON.stringify(body, null, ' ')) } catch (e) { setResponse( '// There was an error with the request. Please contact support@clerk.dev' ) } } return ( <div className={styles.backend}> <h2>API request example</h2> <div className={styles.card}> <button target="_blank" rel="noreferrer" className={styles.cardContent} onClick={() => makeRequest()} > <img src="/icons/server.svg" /> <div> <h3>fetch('/api/getAuthenticatedUserId')</h3> <p> Retrieve the user ID of the signed in user, or null if there is no user </p> </div> <div className={styles.arrow}> <img src="/icons/download.svg" /> </div> </button> </div> <h4> Response <em> <SignedIn> You are signed in, so the request will return your user ID </SignedIn> <SignedOut> You are signed out, so the request will return null </SignedOut> </em> </h4> <pre> <code className="language-js">{response}</code> </pre> <h4>pages/api/getAuthenticatedUserId.js</h4> <pre> <code className="language-js">{apiSample}</code> </pre> </div> ) } // Footer component const Footer = () => ( <footer className={styles.footer}> Powered by{' '} <a href="https://clerk.dev" target="_blank" rel="noopener noreferrer"> <img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} /> </a> + <a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer"> <img src="/nextjs.svg" alt="Next.js" className={styles.logo} /> </a> </footer> ) const Home = () => ( <div className={styles.container}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" ></meta> </Head> <Main /> <Footer /> </div> ) export default Home
src/components/ProgressBar/ProgressBar.js
vonZ/rc-vvz
import React from 'react'; import PropTypes from 'prop-types'; class ProgressBar extends React.Component {   getColor = (percent) => {     if (this.props.percent === 100) return 'green';     return this.props.percent > 50 ? 'lightgreen' : 'red';   } getWidthAsPercentOfTotalWidth = () => { return parseInt(this.props.width * (this.props.percent / 100), 10); }   render() {     const {percent, width, height} = this.props;     return (       <div style={{border: 'solid 1px lightgray', width: width}}>         <div style={{           width: this.getWidthAsPercentOfTotalWidth(),           height,           backgroundColor: this.getColor(percent)         }} />       </div>     );   } } ProgressBar.propTypes = { /** Percent of progress completed */ percent: PropTypes.number.isRequired, /** Bar width */ width: PropTypes.number.isRequired, /** Bar height */ height: PropTypes.number }; ProgressBar.defaultProps = { height: 5 }; export default ProgressBar;
dokomoforms/static/src/survey/js/components/__tests__/Splash-tests.js
SEL-Columbia/dokomoforms
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; // jest.autoMockOff(); // a noop function useful for passing into components that require it. var noop = () => {}; describe('Splash', () => { var Splash; beforeEach(function() { jest.dontMock('../Splash.js'); Splash = require('../Splash'); }); it('does nothing', () => { }); });
src/containers/HomeContainer.js
hoppispace/hoppi-space-web-app
import React from 'react'; import { URL_FACEBOOK, URL_INSTAGRAM, URL_TWITTER } from "../constants"; import SearchForm from '../components/Search/SearchForm'; const HomePage = () => { return ( <main id="home-container"> <div className="container-fluid"> <div className="row"> <div id="lead" className="col-lg-12 align-center"> <div id="social-media-links"> <a href={URL_FACEBOOK}><img src={require("../assets/icons/socialmedia/icons8-facebook.svg")}/></a> <a href={URL_INSTAGRAM}><img src={require("../assets/icons/socialmedia/icons8-instagram.svg")}/></a> <a href={URL_TWITTER}><img src={require("../assets/icons/socialmedia/icons8-twitter.svg")}/></a> </div> <h1 className="hoppiSpaceBrandName">hoppi space</h1> <h4>Connecting the artist within to the space you are without</h4> <SearchForm/> </div> </div> <div className="row"> <div id="how-it-works" className="col-lg-12"> <h2>How It Works</h2> <h3>Browse, Book, Pay</h3> <hr/> <p className="lead">We are your new favorite local coffee shop community board. Browse hundreds of available workshops in your area or worldwide using our fast and efficient search engine. We optimize results with your craft needs, tools, and budget in mind. When you've found "the one", our effortless booking system will relay your request to our owners for confirmation, and utilizing our secure Braintree-based payment system, make your payment. <span className="font-weight-bold font-italic">Welcome home!</span></p> </div> </div> </div> </main> ); }; export default HomePage;
code/web/node_modules/react-bootstrap/es/Label.js
zyxcambridge/RecordExistence
import _Object$values from 'babel-runtime/core-js/object/values'; 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, bsStyles, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { State, Style } from './utils/StyleConfig'; var Label = function (_React$Component) { _inherits(Label, _React$Component); function Label() { _classCallCheck(this, Label); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Label.prototype.hasContent = function hasContent(children) { var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Label.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), { // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return React.createElement( 'span', _extends({}, elementProps, { className: classNames(className, classes) }), children ); }; return Label; }(React.Component); export default bsClass('label', bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY]), Style.DEFAULT, Label));
packages/ringcentral-widgets/components/CallListV2/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import { List } from 'react-virtualized'; import CallItem from '../CallItem'; import NoCalls from '../NoCalls'; export default class CallListV2 extends React.PureComponent { constructor(props) { super(props); this.state = { extendedIndex: null, }; this._list = React.createRef(); } componentWillReceiveProps(nextProps) { const { extendedIndex } = this.state; if ( extendedIndex !== null && this.props.calls[extendedIndex] !== nextProps.calls[extendedIndex] ) { this._setExtendedIndex(null); } } _setExtendedIndex = (extendedIndex) => { this.setState( { extendedIndex, }, () => { if (this._list && this._list.current) { this._list.current.recomputeRowHeights(0); } }, ); }; _onSizeChanged = (index) => { if (this.state.extendedIndex === index) { this._setExtendedIndex(null); } else { this._setExtendedIndex(index); } }; _renderRowHeight = ({ index }) => { // If we don't add extra height for the last item // the toggle button will be cut off const margin = index === this.props.calls.length - 1 ? 15 : 0; const rowHeight = index === this.state.extendedIndex ? this.props.extendedRowHeight : this.props.rowHeight; return rowHeight + margin; }; _rowRender = ({ index, key, style }) => { const { className, brand, currentLocale, calls, areaCode, countryCode, onViewContact, onCreateContact, createEntityTypes, onLogCall, onClickToDial, onClickToSms, isLoggedContact, disableLinks, disableCallButton, disableClickToDial, outboundSmsPermission, internalSmsPermission, active, dateTimeFormatter, loggingMap, webphoneAnswer, webphoneReject, webphoneHangup, webphoneResume, enableContactFallback, autoLog, showContactDisplayPlaceholder, sourceIcons, phoneTypeRenderer, phoneSourceNameRenderer, renderContactName, renderExtraButton, contactDisplayStyle, externalViewEntity, externalHasEntity, readTextPermission, } = this.props; let content; if (index >= calls.length) { content = ( <div className={className}> <NoCalls currentLocale={currentLocale} active={active} /> </div> ); } else { const call = calls[index]; content = ( <CallItem key={call.id} renderIndex={index} extended={this.state.extendedIndex === index} style={style} call={call} currentLocale={currentLocale} brand={brand} areaCode={areaCode} countryCode={countryCode} onViewContact={onViewContact} onCreateContact={onCreateContact} createEntityTypes={createEntityTypes} onLogCall={onLogCall} onClickToDial={onClickToDial} onClickToSms={onClickToSms} isLoggedContact={isLoggedContact} disableLinks={disableLinks} disableCallButton={disableCallButton} disableClickToDial={disableClickToDial} outboundSmsPermission={outboundSmsPermission} internalSmsPermission={internalSmsPermission} active={active} dateTimeFormatter={dateTimeFormatter} isLogging={!!loggingMap[call.sessionId]} webphoneAnswer={webphoneAnswer} webphoneReject={webphoneReject} webphoneHangup={webphoneHangup} webphoneResume={webphoneResume} enableContactFallback={enableContactFallback} autoLog={autoLog} showContactDisplayPlaceholder={showContactDisplayPlaceholder} sourceIcons={sourceIcons} phoneTypeRenderer={phoneTypeRenderer} phoneSourceNameRenderer={phoneSourceNameRenderer} renderContactName={renderContactName} renderExtraButton={renderExtraButton} contactDisplayStyle={contactDisplayStyle} externalViewEntity={externalViewEntity} externalHasEntity={externalHasEntity} readTextPermission={readTextPermission} onSizeChanged={this._onSizeChanged} // disable animation when rendered with react-virtualized withAnimation={false} /> ); } return ( <div key={key} style={style}> {content} </div> ); }; noRowsRender = () => { const { currentLocale, active } = this.props; return <NoCalls currentLocale={currentLocale} active={active} />; }; render() { const { width, height, calls, className } = this.props; return ( <div> <List style={{ outline: 'none', overflowY: 'auto' }} containerStyle={{ overflow: 'visible' }} ref={this._list} width={width} height={height} overscanRowCount={15} className={className} rowCount={calls.length} rowHeight={this._renderRowHeight} rowRenderer={this._rowRender} noRowsRenderer={this.noRowsRender} /> </div> ); } } CallListV2.propTypes = { className: PropTypes.string, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, brand: PropTypes.string.isRequired, currentLocale: PropTypes.string.isRequired, calls: PropTypes.arrayOf(CallItem.propTypes.call).isRequired, active: PropTypes.bool, areaCode: PropTypes.string.isRequired, countryCode: PropTypes.string.isRequired, onViewContact: PropTypes.func, onCreateContact: PropTypes.func, createEntityTypes: PropTypes.array, onLogCall: PropTypes.func, onClickToDial: PropTypes.func, onClickToSms: PropTypes.func, isLoggedContact: PropTypes.func, loggingMap: PropTypes.object, disableLinks: PropTypes.bool, disableCallButton: PropTypes.bool, disableClickToDial: PropTypes.bool, outboundSmsPermission: PropTypes.bool, internalSmsPermission: PropTypes.bool, dateTimeFormatter: PropTypes.func.isRequired, webphoneAnswer: PropTypes.func, webphoneReject: PropTypes.func, webphoneHangup: PropTypes.func, webphoneResume: PropTypes.func, enableContactFallback: PropTypes.bool, autoLog: PropTypes.bool, showContactDisplayPlaceholder: PropTypes.bool, sourceIcons: PropTypes.object, phoneTypeRenderer: PropTypes.func, phoneSourceNameRenderer: PropTypes.func, renderContactName: PropTypes.func, renderExtraButton: PropTypes.func, contactDisplayStyle: PropTypes.string, externalViewEntity: PropTypes.func, externalHasEntity: PropTypes.func, readTextPermission: PropTypes.bool, rowHeight: PropTypes.number, extendedRowHeight: PropTypes.number, }; CallListV2.defaultProps = { className: null, active: false, disableLinks: false, disableCallButton: false, disableClickToDial: false, outboundSmsPermission: false, internalSmsPermission: false, onViewContact: undefined, onCreateContact: undefined, createEntityTypes: undefined, onLogCall: undefined, isLoggedContact: undefined, onClickToDial: undefined, onClickToSms: undefined, loggingMap: {}, webphoneAnswer: undefined, webphoneReject: undefined, webphoneHangup: undefined, webphoneResume: undefined, enableContactFallback: undefined, showContactDisplayPlaceholder: true, autoLog: false, sourceIcons: undefined, phoneTypeRenderer: undefined, phoneSourceNameRenderer: undefined, renderContactName: undefined, renderExtraButton: undefined, contactDisplayStyle: undefined, externalViewEntity: undefined, externalHasEntity: undefined, readTextPermission: true, rowHeight: 65, extendedRowHeight: 130, };
src/svg-icons/av/fiber-new.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFiberNew = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zM8.5 15H7.3l-2.55-3.5V15H3.5V9h1.25l2.5 3.5V9H8.5v6zm5-4.74H11v1.12h2.5v1.26H11v1.11h2.5V15h-4V9h4v1.26zm7 3.74c0 .55-.45 1-1 1h-4c-.55 0-1-.45-1-1V9h1.25v4.51h1.13V9.99h1.25v3.51h1.12V9h1.25v5z"/> </SvgIcon> ); AvFiberNew = pure(AvFiberNew); AvFiberNew.displayName = 'AvFiberNew'; AvFiberNew.muiName = 'SvgIcon'; export default AvFiberNew;
examples/todomvc/containers/TodoApp.js
rt2zz/redux
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { Connector } from 'redux/react'; import Header from '../components/Header'; import MainSection from '../components/MainSection'; import * as TodoActions from '../actions/TodoActions'; export default class TodoApp extends Component { render() { return ( <Connector select={state => ({ todos: state.todos })}> {this.renderChild} </Connector> ); } renderChild({ todos, dispatch }) { const actions = bindActionCreators(TodoActions, dispatch); return ( <div> <Header addTodo={actions.addTodo} /> <MainSection todos={todos} actions={actions} /> </div> ); } }
src/svg-icons/action/perm-device-information.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermDeviceInformation = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/> </SvgIcon> ); ActionPermDeviceInformation = pure(ActionPermDeviceInformation); ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation'; ActionPermDeviceInformation.muiName = 'SvgIcon'; export default ActionPermDeviceInformation;
node_modules/react-router/es6/IndexRedirect.js
wojtczat/WeatherApp
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import Redirect from './Redirect'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ var IndexRedirect = React.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRedirect;
frontend/src/Settings/ImportLists/ImportLists/ImportLists.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Card from 'Components/Card'; import FieldSet from 'Components/FieldSet'; import Icon from 'Components/Icon'; import PageSectionContent from 'Components/Page/PageSectionContent'; import { icons } from 'Helpers/Props'; import AddImportListModal from './AddImportListModal'; import EditImportListModalConnector from './EditImportListModalConnector'; import ImportList from './ImportList'; import styles from './ImportLists.css'; class ImportLists extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isAddImportListModalOpen: false, isEditImportListModalOpen: false }; } // // Listeners onAddImportListPress = () => { this.setState({ isAddImportListModalOpen: true }); } onAddImportListModalClose = ({ listSelected = false } = {}) => { this.setState({ isAddImportListModalOpen: false, isEditImportListModalOpen: listSelected }); } onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); } // // Render render() { const { items, onConfirmDeleteImportList, ...otherProps } = this.props; const { isAddImportListModalOpen, isEditImportListModalOpen } = this.state; return ( <FieldSet legend="Import Lists" > <PageSectionContent errorMessage="Unable to load Lists" {...otherProps} > <div className={styles.lists}> { items.map((item) => { return ( <ImportList key={item.id} {...item} onConfirmDeleteImportList={onConfirmDeleteImportList} /> ); }) } <Card className={styles.addList} onPress={this.onAddImportListPress} > <div className={styles.center}> <Icon name={icons.ADD} size={45} /> </div> </Card> </div> <AddImportListModal isOpen={isAddImportListModalOpen} onModalClose={this.onAddImportListModalClose} /> <EditImportListModalConnector isOpen={isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} /> </PageSectionContent> </FieldSet> ); } } ImportLists.propTypes = { isFetching: PropTypes.bool.isRequired, error: PropTypes.object, items: PropTypes.arrayOf(PropTypes.object).isRequired, onConfirmDeleteImportList: PropTypes.func.isRequired }; export default ImportLists;
screens/PersonDetail.js
FindEarth/app
import React from 'react' import PropTypes from 'prop-types' import Colors from '../constants/Colors' import Styles from '../styles/PersonDetail' import HeaderTitle from '../components/HeaderTitle' import PersonDetailView from '../components/PersonDetailView' import { Share } from 'react-native' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import * as allActions from '../actions' const rightIcon = { ios: 'ios-share-outline', android: 'md-share', onPress: personShare, } const shareOptions = { url: 'https://find.earth/', name: 'personas perdidas', } function personShare() { Share.share({ message: `Ayudanos a encontrar a ${shareOptions.name}`, url: shareOptions.url, title: `Compartir ${shareOptions.name}`, }, { dialogTitle: 'Compartir', } ) .then((result) => { if (result.action === Share.sharedAction) { if (result.activityType) { console.log('Shared with an activityType: ', result.activityType) } else { console.log('Shared') } } else if (result.action === Share.dismissedAction) { console.log('Dismissed') } }) .catch((error) => console.log(error.message)) } class PersonDetail extends React.Component { static propTypes = { personSelected: PropTypes.object.isRequired, refreshingPerson: PropTypes.bool.isRequired, errorRefreshingPerson: PropTypes.bool.isRequired, refreshPersonDetail: PropTypes.func.isRequired, } static route = { navigationBar: { title: 'Descripción', backgroundColor: Colors.white, borderBottomWidth: 1, tintColor: Colors.tintColor, renderTitle: (route) => ( <HeaderTitle title={route.params.person.name} rightIcon={rightIcon} /> ), }, } componentWillMount() { this.updateHeaderName() } componentWillReceiveProps() { this.updateHeaderName() } updateHeaderName = () => { const person = this.props.personSelected if (person) { this.props.route.params.person.name = person.name shareOptions.name = person.name shareOptions.url = `https://find.earth/person/${person._slug}` } } onRefreshPerson = () => { this.props.refreshPersonDetail() } render() { return ( <PersonDetailView styles={Styles} person={this.props.personSelected} refreshingPerson={this.props.refreshingPerson} errorRefreshingPerson={this.props.errorRefreshingPerson} onRefreshPerson={this.onRefreshPerson} /> ) } } function mapStateToProps (state) { return { personSelected: state.personDetail.personSelected, refreshingPerson: state.personDetail.refreshingPerson, errorRefreshingPerson: state.personDetail.errorRefreshingPerson, } } function mapDispatchToProps (dispatch) { const actions = bindActionCreators(allActions, dispatch) return { refreshPersonDetail: actions.refreshPersonDetail, } } export default connect( mapStateToProps, mapDispatchToProps )(PersonDetail)
src/mongostick/frontend/src/screens/Collections.js
RockingRolli/mongostick
import React from 'react' import { Col, Row, Table } from 'antd' import { connect } from 'react-redux' import { formatBytes } from '../lib/mongodb' class Collections extends React.Component { getColumns = () => { return [ { title: 'Name', dataIndex: 'ns', key: 'ns', }, { title: 'storageSize', dataIndex: 'storageSize', key:'storageSize', render: text => formatBytes(text), sorter: (a, b) => a.storageSize - b.storageSize, }, { title:'Size', dataIndex: 'size', key:'size', render: text => formatBytes(text), sorter: (a, b) => a.size - b.size, }, { title:'count', dataIndex: 'count', key:'count', render: text => text.toLocaleString(), sorter: (a, b) => a.count - b.count, }, { title:'totalIndexSize', dataIndex: 'totalIndexSize', key:'totalIndexSize', render: text => formatBytes(text), sorter: (a, b) => a.totalIndexSize - b.totalIndexSize, }, { title:'nindexes', dataIndex: 'nindexes', key:'nindexes', sorter: (a, b) => a.nindexes - b.nindexes, }, { title:'avgObjSize', dataIndex: 'avgObjSize', key:'avgObjSize', render: text => formatBytes(text), sorter: (a, b) => a.avgObjSize - b.avgObjSize, }, { title:'capped', dataIndex: 'capped', key:'capped', render: text => text.toString(), }, ] } getDataSource = () => { const { databases } = this.props const { db_name } = this.props.match.params const database = databases[db_name] if (database === undefined) { return [] } return Object.keys(database.collections).map((index) => database.collections[index]) } render() { return ( <div> {this.props.children} <Row style={{ background: '#fff' }}> <Col span={24}> <Table dataSource={this.getDataSource()} columns={this.getColumns()} rowKey={record => record.ns} /> </Col> </Row> </div> ) } } const mapStateToProps = store => { return { databases: store.databases, } } export default connect(mapStateToProps)(Collections)
app/javascript/mastodon/features/status/components/action_bar.js
Arukas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from '../../../components/icon_button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; import { me } from '../../../initial_state'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, mute: { id: 'status.mute', defaultMessage: 'Mute @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, block: { id: 'status.block', defaultMessage: 'Block @{name}' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, share: { id: 'status.share', defaultMessage: 'Share' }, pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, embed: { id: 'status.embed', defaultMessage: 'Embed' }, }); @injectIntl export default class ActionBar extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onReply: PropTypes.func.isRequired, onReblog: PropTypes.func.isRequired, onFavourite: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onMute: PropTypes.func, onMuteConversation: PropTypes.func, onBlock: PropTypes.func, onReport: PropTypes.func, onPin: PropTypes.func, onEmbed: PropTypes.func, intl: PropTypes.object.isRequired, }; handleReplyClick = () => { this.props.onReply(this.props.status); } handleReblogClick = (e) => { this.props.onReblog(this.props.status, e); } handleFavouriteClick = () => { this.props.onFavourite(this.props.status); } handleDeleteClick = () => { this.props.onDelete(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { this.props.onMute(this.props.status.get('account')); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } handleBlockClick = () => { this.props.onBlock(this.props.status.get('account')); } handleReport = () => { this.props.onReport(this.props.status); } handlePinClick = () => { this.props.onPin(this.props.status); } handleShare = () => { navigator.share({ text: this.props.status.get('search_index'), url: this.props.status.get('url'), }); } handleEmbed = () => { this.props.onEmbed(this.props.status); } render () { const { status, intl } = this.props; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const mutingConversation = status.get('muted'); let menu = []; if (publicStatus) { menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed }); } if (me === status.getIn(['account', 'id'])) { if (publicStatus) { menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick }); } menu.push(null); menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick }); menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick }); menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport }); } const shareButton = ('share' in navigator) && status.get('visibility') === 'public' && ( <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShare} /></div> ); let reblogIcon = 'retweet'; if (status.get('visibility') === 'direct') reblogIcon = 'envelope'; else if (status.get('visibility') === 'private') reblogIcon = 'lock'; let reblog_disabled = (status.get('visibility') === 'direct' || status.get('visibility') === 'private'); return ( <div className='detailed-status__action-bar'> <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.reply)} icon={status.get('in_reply_to_id', null) === null ? 'reply' : 'reply-all'} onClick={this.handleReplyClick} /></div> <div className='detailed-status__button'><IconButton disabled={reblog_disabled} active={status.get('reblogged')} title={reblog_disabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /></div> <div className='detailed-status__button'><IconButton animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} activeStyle={{ color: '#ca8f04' }} /></div> {shareButton} <div className='detailed-status__action-bar-dropdown'> <DropdownMenuContainer size={18} icon='ellipsis-h' items={menu} direction='left' title='More' /> </div> </div> ); } }
packages/reactor-kitchensink/src/examples/D3/Hierarchy/ConfigurablePivotTreeMap/ConfigurablePivotTreeMap.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Toolbar, Button, Spacer } from '@extjs/ext-react'; import { PivotD3Container } from '@extjs/ext-react-pivot-d3'; import createData from './createData'; import './styles.css'; const regions = { "Belgium": 'Europe', "Netherlands": 'Europe', "United Kingdom": 'Europe', "Canada": 'North America', "United States": 'North America', "Australia": 'Australia' }; Ext.require(['Ext.pivot.d3.TreeMap']); export default class ConfigurablePivotTreeMap extends Component { store = Ext.create('Ext.data.TreeStore', { fields: [ {name: 'id', type: 'string'}, {name: 'company', type: 'string'}, {name: 'country', type: 'string'}, {name: 'person', type: 'string'}, {name: 'date', type: 'date', dateFormat: 'c'}, {name: 'value', type: 'float'}, {name: 'quantity', type: 'float'}, { name: 'year', calculate: function(data){ return parseInt(Ext.Date.format(data.date, "Y"), 10); } },{ name: 'month', calculate: function(data){ return parseInt(Ext.Date.format(data.date, "m"), 10) - 1; } },{ name: 'continent', calculate: function(data){ return regions[data.country]; } } ], data: createData() }) showConfigurator = () => this.refs.mainCtn.showConfigurator() onShowConfigPanel = panel => { panel.getLeftAxisHeader().getTitle().setText('Tree labels'); panel.setTopAxisContainerVisible(false); } onBeforeAddConfigField = (panel, config) => { const dest = config.toContainer, store = dest.getStore(); if (dest.getFieldType() !== 'all' && store.getCount() >= 1) { // this will force single fields on both axis and aggregate store.removeAll(); } } onShowFieldSettings = (panel, config) => { const align = config.container.down('[name=align]'); // hide the alignment field in settings since it's useless if(align) { align.hide(); } } render() { return ( <PivotD3Container shadow ref="mainCtn" onShowConfigPanel={this.onShowConfigPanel} onBeforeMoveConfigField={this.onBeforeAddConfigField} onShowConfigFieldSettings={this.onShowFieldSettings} matrix={{ store: this.store, aggregate: [{ dataIndex: 'value', header: 'Value', aggregator: 'sum' }], leftAxis: [{ dataIndex: 'person', header: 'Person' }] }} drawing={{xtype: 'pivottreemap'}} configurator={{ // It is possible to configure a list of fields that can be used to configure the pivot matrix // If no fields list is supplied then all fields from the Store model are fetched automatically fields: [{ dataIndex: 'quantity', header: 'Qty', // You can even provide a default aggregator function to be used when this field is dropped // on the agg dimensions aggregator: 'sum', formatter: 'number("0")', settings: { // Define here in which areas this field could be used allowed: ['aggregate'], // Set a custom style for this field to inform the user that it can be dragged only to "Values" style: { fontWeight: 'bold' }, // Define here custom formatters that ca be used on this dimension formatters: { '0': 'number("0")', '0%': 'number("0%")' } } }, { dataIndex: 'value', header: 'Value', settings: { // Define here in which areas this field could be used allowed: 'aggregate', // Define here what aggregator functions can be used when this field is // used as an aggregate dimension aggregators: ['sum', 'avg', 'count'], // Set a custom style for this field to inform the user that it can be dragged only to "Values" style: { fontWeight: 'bold' }, // Define here custom formatters that ca be used on this dimension formatters: { '0': 'number("0")', '0.00': 'number("0.00")', '0,000.00': 'number("0,000.00")', '0%': 'number("0%")', '0.00%': 'number("0.00%")' } } }, { dataIndex: 'company', header: 'Company', settings: { // Define here what aggregator functions can be used when this field is // used as an aggregate dimension aggregators: ['count'] } }, { dataIndex: 'country', header: 'Country', settings: { // Define here what aggregator functions can be used when this field is // used as an aggregate dimension aggregators: ['count'] } }, { dataIndex: 'person', header: 'Person', settings: { // Define here what aggregator functions can be used when this field is // used as an aggregate dimension aggregators: 'count' } }, { dataIndex: 'year', header: 'Year', settings: { // Define here in which areas this field could be used allowed: ['leftAxis', 'topAxis'] } }, { dataIndex: 'month', header: 'Month', labelRenderer: 'monthLabelRenderer', settings: { // Define here in which areas this field could be used allowed: ['leftAxis', 'topAxis'] } }] }} > <Toolbar docked="top"> <Spacer/> <Button text="Show configurator" handler={this.showConfigurator}/> </Toolbar> </PivotD3Container> ) } }
src/svg-icons/hardware/keyboard-return.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardReturn = (props) => ( <SvgIcon {...props}> <path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/> </SvgIcon> ); HardwareKeyboardReturn = pure(HardwareKeyboardReturn); HardwareKeyboardReturn.displayName = 'HardwareKeyboardReturn'; HardwareKeyboardReturn.muiName = 'SvgIcon'; export default HardwareKeyboardReturn;
app/components/DrawerHeader/DrawerHeader.js
danielzy95/oaa-chat
import React from 'react' import { observer } from 'mobx-react' import IconButton from 'material-ui/IconButton' import styles from './DrawerHeader.css' const DrawerHeader = ({ title, backgroundColor, color, close }) => ( <div class={styles.root} style={{ backgroundColor: backgroundColor || '#493553' }}> <IconButton iconClassName="material-icons" iconStyle={{color: color || '#7B85AD'}} style={{ top: '42%' }} onClick={close}> arrow_back </IconButton> <span class={styles.title}>{title}</span> </div> ) export default observer(DrawerHeader)
src/app.js
williambryan777/react-blog-with-es6
import React, { Component } from 'react'; import { BlogBox } from './components'; import $ from 'jquery'; class App extends Component { constructor(props) { super(props); this.state = { blogList: [], }; } componentDidMount() { const postUrl = '/Social/Home/GetHotMicroBlogs'; const queryParams = { rcount: 0, startId: 0, pageIndex: 1, time: 24, pageSize: 15, }; $.post(postUrl, queryParams, (response) => { const listItems = response.list.Items; this.setState({ blogList: listItems, }); }); } render() { return ( <div> <BlogBox blogList={this.state.blogList} /> </div> ); } } export default App;
app/javascript/mastodon/features/ui/components/bundle_modal_error.js
cobodo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ error: { id: 'bundle_modal_error.message', defaultMessage: 'Something went wrong while loading this component.' }, retry: { id: 'bundle_modal_error.retry', defaultMessage: 'Try again' }, close: { id: 'bundle_modal_error.close', defaultMessage: 'Close' }, }); class BundleModalError extends React.PureComponent { static propTypes = { onRetry: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } handleRetry = () => { this.props.onRetry(); } render () { const { onClose, intl: { formatMessage } } = this.props; // Keep the markup in sync with <ModalLoading /> // (make sure they have the same dimensions) return ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <IconButton title={formatMessage(messages.retry)} icon='refresh' onClick={this.handleRetry} size={64} /> {formatMessage(messages.error)} </div> <div className='error-modal__footer'> <div> <button onClick={onClose} className='error-modal__nav onboarding-modal__skip' > {formatMessage(messages.close)} </button> </div> </div> </div> ); } } export default injectIntl(BundleModalError);
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js
gutenye/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import logo from './assets/logo.svg'; export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
analysis/shamanelemental/src/modules/features/Overload.js
yajinni/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { SpellIcon } from 'interface'; import Analyzer from 'parser/core/Analyzer'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import StatisticBox, { STATISTIC_ORDER } from 'parser/ui/StatisticBox'; import Events from 'parser/core/Events'; class Overload extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; spells = []; statisticOrder = STATISTIC_ORDER.OPTIONAL(); constructor(...args) { super(...args); this.active = true; this.getAbility = spellId => this.abilityTracker.getAbility(spellId); this.hasIcefury = this.selectedCombatant.hasTalent(SPELLS.ICEFURY_TALENT.id); this.hasElementalBlast = this.selectedCombatant.hasTalent(SPELLS.ELEMENTAL_BLAST_TALENT.id); this.spells = [ this.getHits(SPELLS.LAVA_BURST_OVERLOAD_DAMAGE.id, SPELLS.LAVA_BURST_DAMAGE.id), this.getHits(SPELLS.LIGHTNING_BOLT_OVERLOAD_HIT.id, SPELLS.LIGHTNING_BOLT.id), this.getHits(SPELLS.CHAIN_LIGHTNING_OVERLOAD.id, SPELLS.CHAIN_LIGHTNING.id), this.hasElementalBlast && this.getHits(SPELLS.ELEMENTAL_BLAST_OVERLOAD.id, SPELLS.ELEMENTAL_BLAST_TALENT.id), this.hasIcefury && this.getHits(SPELLS.ICEFURY_OVERLOAD.id, SPELLS.ICEFURY_TALENT.id), ]; this.addEventListener(Events.fightend, this.onFightend); } getHits(overloadSpellId, normalSpellId) { const overloadSpell = this.getAbility(overloadSpellId); const normalSpell = this.getAbility(normalSpellId); const normal = !normalSpell.ability ? 0 : normalSpell.damageHits; const overloads = !overloadSpell.ability ? 0 : overloadSpell.damageHits; return { id: overloadSpellId, name: !normalSpell.ability ? 'a spell' : normalSpell.ability.name, normal, overloads, percent: overloads / normal, }; } onFightend() { this.spells = [ this.getHits(SPELLS.LAVA_BURST_OVERLOAD_DAMAGE.id, SPELLS.LAVA_BURST_DAMAGE.id), this.getHits(SPELLS.LIGHTNING_BOLT_OVERLOAD_HIT.id, SPELLS.LIGHTNING_BOLT.id), this.getHits(SPELLS.CHAIN_LIGHTNING_OVERLOAD.id, SPELLS.CHAIN_LIGHTNING.id), this.hasElementalBlast && this.getHits(SPELLS.ELEMENTAL_BLAST_OVERLOAD.id, SPELLS.ELEMENTAL_BLAST_TALENT.id), this.hasIcefury && this.getHits(SPELLS.ICEFURY_OVERLOAD.id, SPELLS.ICEFURY_TALENT.id), ]; } renderOverloads(spell) { if (!spell) { return null; } return ( <li key={spell.id}> <SpellIcon id={spell.id} style={{ height: '1.3em', marginTop: '-.1em', }} /> <span style={{ display: 'inline-block', textAlign: 'left', marginLeft: '0.5em' }}> {spell.overloads} / {spell.normal} </span> </li> ); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.ELEMENTAL_MASTERY.id} />} value={( <ul style={{ listStyle: 'none', paddingLeft: 0 }}> {this.spells.map(spell => this.renderOverloads(spell))} </ul> )} label="Overload procs" tooltip={`${this.spells[0].overloads} / ${this.spells[0].normal} means you hit the target ${this.spells[0].normal} times with ${this.spells[0].name} and got ${this.spells[0].overloads} extra overload hits.`} /> ); } } export default Overload;
docs-ui/components/alertLink.stories.js
beeftornado/sentry
import React from 'react'; import {withInfo} from '@storybook/addon-info'; import AlertLink from 'app/components/alertLink'; import {IconDocs, IconGeneric, IconMail, IconStack, IconStar} from 'app/icons'; export default { title: 'Core/Alerts/AlertLink', }; export const Default = withInfo( 'A way to loudly link between different parts of the application' )(() => [ <AlertLink to="/settings/account/notifications" key="1"> Check out the notifications settings panel. </AlertLink>, <AlertLink to="/settings/account/notifications" priority="error" key="2"> Do not forget to read the docs ya dum dum! </AlertLink>, <AlertLink to="/settings/account/notifications" priority="info" key="3"> Install this thing or else! </AlertLink>, <AlertLink to="/settings/account/notifications" priority="success" key="4"> Gj you did it. Now go here. </AlertLink>, <AlertLink to="/settings/account/notifications" priority="muted" key="5"> I am saying nothing, ok? </AlertLink>, ]); Default.story = { name: 'default', }; export const WithAnIcon = withInfo('You can optionally pass an icon src')(() => [ <AlertLink to="/settings/account/notifications" icon={<IconMail />} key="1"> Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini. </AlertLink>, <AlertLink to="/settings/account/notifications" icon={<IconDocs />} priority="error" key="2" > Do not forget to read the docs ya dum dum! </AlertLink>, <AlertLink to="/settings/account/notifications" icon={<IconStack />} priority="info" key="3" > Install this thing or else! </AlertLink>, <AlertLink to="/settings/account/notifications" icon={<IconStar />} priority="success" key="4" > Gj you did it. Now go here. </AlertLink>, <AlertLink to="/settings/account/notifications" icon={<IconGeneric />} priority="muted" key="5" > I am saying nothing, ok? </AlertLink>, ]); WithAnIcon.story = { name: 'with an icon', }; export const Small = withInfo('You can optionally pass an icon src')(() => [ <AlertLink to="/settings/account/notifications" size="small" key="1"> Check out the notifications settings panel. </AlertLink>, <AlertLink to="/settings/account/notifications" priority="error" size="small" key="2"> Do not forget to read the docs ya dum dum! </AlertLink>, <AlertLink to="/settings/account/notifications" priority="info" size="small" key="3"> Install this thing or else! </AlertLink>, <AlertLink to="/settings/account/notifications" priority="success" size="small" key="4"> Gj you did it. Now go here. </AlertLink>, <AlertLink to="/settings/account/notifications" priority="muted" size="small" key="5"> I am saying nothing, ok? </AlertLink>, ]); Small.story = { name: 'small', };
app/components/CollectionHeader.js
jackokerman/react-discogs-dj
import React from 'react'; import HeaderColumn from './HeaderColumn.js'; const columns = [ { column: 'artist', display: 'Artist' }, { column: 'title', display: 'Title' }, { column: 'year', display: 'Year' }, { column: 'added', display: 'Added' }, ]; const CollectionHeader = props => ( <tr> {columns.map((column, i) => { if (props.sortColumn === column.column) { return ( <HeaderColumn key={i} handleSort={props.handleSort} column={column.column} sort={props.sortOrder} > {column.display} </HeaderColumn> ); } return ( <HeaderColumn key={i} handleSort={props.handleSort} column={column.column} > {column.display} </HeaderColumn> ); })} </tr> ); CollectionHeader.propTypes = { sortColumn: React.PropTypes.string.isRequired, sortOrder: React.PropTypes.string.isRequired, handleSort: React.PropTypes.func.isRequired, }; export default CollectionHeader;
src/components/Hello/index.js
lijinfengworm/ant-design-reactjs
import React from 'react'; import './index.less'; /** * 测试用 */ class Hello extends React.PureComponent { render() { return <div><h1 className="testStyle">Hello, React!</h1></div>; } } export default Hello;
app/components/welcome0.js
nyc-bobolinks-2016/TemoApp
import React, { Component } from 'react'; import { Navigator, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'; import SendBird from 'sendbird' import NavMenu from './navMenu'; export default class Signup extends Component { constructor() { super(); console.disableYellowBox = true; global.lastRoute = "" this.state = { username: '', phone: '' } } handleChangeUsername(value) { this.setState({username: value}) global.currentUser = value } handleChangePhone(value) { this.setState({phone: value}) global.currentPhone = value } handleSignup() { sb = new SendBird({ appId: '6042A607-C497-460C-B8E8-9934DF5D8529' }) var _self = this sb.connect(_self.state.phone, function (user, error) {}); sb.updateCurrentUserInfo(this.state.username, '', function(response, error) { }); fetch('https://temo-api.herokuapp.com/users', { method: 'post', headers: { 'Accept': 'application/json','Content-Type': 'application/json'}, body: JSON.stringify({ username: this.state.username, phone: this.state.phone }) }) .then((response) => response.json()) .then((responseJson) => { if (responseJson.created_at != null) { console.log(responseJson) this.props.navigator.push({name: 'conversations'}) } else { console.log("no invalid phone number") } }) } handleLogin() { sb = new SendBird({ appId: '6042A607-C497-460C-B8E8-9934DF5D8529' }) var _self = this sb.connect(_self.state.phone, function (user, error) {}); sb.updateCurrentUserInfo(this.state.username, '', function(response, error) { }); fetch('https://temo-api.herokuapp.com/users/login', { method: 'post', headers: { 'Accept': 'application/json','Content-Type': 'application/json'}, body: JSON.stringify({ username: this.state.username, phone: this.state.phone }) }) .then((response) => response.json()) .then((responseJson) => { if (responseJson.created_at) { console.log(responseJson) this.props.navigator.push({name: 'conversations'}) } else { console.log("no invalid phone number") } }) } render() { return ( <View style={styles.container}> <Text style={styles.header}> Temo </Text> <TextInput style={styles.textInput} placeholder={'Username'} onChangeText={this.handleChangeUsername.bind(this)} value={this.state.username} /> <TextInput style={styles.textInput} placeholder={'Password'} onChangeText={this.handleChangePhone.bind(this)} value={this.state.phone} /> <TouchableOpacity onPress={this.handleLogin.bind(this)}> <Text style={styles.button}>Login</Text> </TouchableOpacity> <TouchableOpacity onPress={this.handleSignup.bind(this)}> <Text style={styles.button}>Sign up</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#e0e0e0', margin: 10, }, header: { fontSize: 100, color: '#00b0ff', margin: 60, fontFamily: 'SnellRoundhand-Bold', marginBottom: 40, }, button: { fontSize: 30, color: '#00b0ff', fontWeight: "100", fontFamily: 'AppleSDGothicNeo-Thin', margin: 5, }, textInput: { padding: 5, alignItems: 'center', justifyContent: 'center', width: 240, height: 40, borderWidth: 1, borderColor: '#757575', marginLeft: 67, marginBottom: 3, borderRadius: 5, backgroundColor: '#e3f2fd' } });
examples/Box.js
casesandberg/workbench
import React from 'react' import _ from 'lodash' import ReactCSS from 'reactcss' const build = (element, property, obj, toApply) => { return toApply ? _.mapValues(obj, (value) => { return { [element]: { [property]: value } } }) : {} } const justifyContent = { left: 'flex-start', center: 'center', right: 'flex-end', spread: 'space-between', } const alignItems = { top: 'flex-start', center: 'center', bottom: 'flex-end', } const flexbox = { // direction row: { // alignment: flexbox align: 'justifyContent', verticalAlign: 'alignItems' }, column: { align: 'alignItems', verticalAlign: 'justifyContent' } } export class Box extends React.Component { classes = () => ({ 'default': { box: { } }, 'row': { box: { display: 'flex', width: '100%', height: '100%', } }, 'column': { box: { display: 'flex', flexDirection: 'column', width: '100%', height: '100%', } }, // ...build('box', 'justifyContent', _.mapKeys(align, (v, k) => (`align-${ k }`)), this.props.row), // ...build('box', 'alignItems', _.mapKeys(verticalAlign, (v, k) => (`align-${ k }`)), this.props.column), // ...build('box', 'alignItems', _.mapKeys(align, (v, k) => (`verticalAlign-${ k }`)), this.props.row), // ...build('box', 'justifyContent', _.mapKeys(verticalAlign, (v, k) => (`verticalAlign-${ k }`)), this.props.column) }) render() { console.log(this.styles().box) return ( <div style={ this.styles().box }>{ this.props.children }</div> ) } } export default ReactCSS(Box)
src/app.js
jeiker26/react
import React from 'react'; import ReactDom from 'react-dom'; import SearchGot from './components/search'; ReactDom.render(<SearchGot />, document.getElementById('app'));
app/components/mapMarker/mapMarkerView.js
UsabilitySoft/Proximater
import React, { Component } from 'react'; import { AppRegistry, Text, View, Image, Button } from 'react-native'; import { styles } from './styles'; const images = require('../images'); export class MapMarkerView extends Component { render() { return ( <View style={styles.container}> <Image source={images.iconMapMarker} style={styles.icon}/> </View> ); } }
client/index.js
gigavinyl/pern-starter
'use-strict'; import { configureStore } from '../shared/redux/store/configureStore'; import { Provider } from 'react-redux'; import postReducer from '../shared/redux/reducers/reducer'; import { render } from 'react-dom'; import React from 'react'; import App from '../shared/container/App'; import PostListView from '../shared/container/PostListView/PostListView'; import PostDetailView from '../shared/container/PostDetailView/PostDetailView'; import { Router, browserHistory } from 'react-router'; import routes from '../shared/routes'; const store = configureStore(window.__INITIAL_STATE__); const history = browserHistory; render(( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ) , document.getElementById('root'));
demo/components/navbar/NavBarOptions.js
f0zze/rosemary-ui
import React from 'react'; import {NavItem, NavHrefItem} from '../../../src'; import OptionsTable from '../../helper/OptionsTable'; export default () => { let commonPropDesc = { active: { values: 'boolean', description: 'Set link to be active' }, right: { values: 'boolean', description: 'Set link to float right' }, withHoverEffect: { values: 'boolean', description: 'on hover will show underline' } }; let navItemPropDesc = { ...commonPropDesc, onClick: { values: 'function', description: 'Is called when btn is clicked' } }; let navHrefItemPropDesc = { ...commonPropDesc }; return ( <div> NavItem: <OptionsTable component={NavItem} propDescription={navItemPropDesc} /> NavHrefItem: <OptionsTable component={NavHrefItem} propDescription={navHrefItemPropDesc} /> </div> ); };
lib/components/App.js
sanack/atom-jq
/** @babel */ import React from 'react' import InputBottomView from './InputBottomView' import { Provider } from 'react-redux' export const App = (store) => ( <Provider store={store}> <InputBottomView /> </Provider> )
test/components/Counter.spec.js
odincov/biguniverse-tools
/* eslint no-unused-expressions: 0 */ import { expect } from 'chai'; import { spy } from 'sinon'; import React from 'react'; import { renderIntoDocument, scryRenderedDOMComponentsWithTag, findRenderedDOMComponentWithTag, Simulate } from 'react-addons-test-utils'; import Counter from '../../src/components/Counter'; function setup() { const actions = { increment: spy(), incrementIfOdd: spy(), incrementAsync: spy(), decrement: spy() }; const component = renderIntoDocument(<Counter counter={1} {...actions} />); return { component: component, actions: actions, buttons: scryRenderedDOMComponentsWithTag(component, 'button').map(button => { return button; }), p: findRenderedDOMComponentWithTag(component, 'p') }; } describe('Counter component', () => { it('should display count', () => { const { p } = setup(); expect(p.textContent).to.match(/^Clicked: 1 times/); }); it('first button should call increment', () => { const { buttons, actions } = setup(); Simulate.click(buttons[0]); expect(actions.increment.called).to.be.true; }); it('second button should call decrement', () => { const { buttons, actions } = setup(); Simulate.click(buttons[1]); expect(actions.decrement.called).to.be.true; }); it('third button should call incrementIfOdd', () => { const { buttons, actions } = setup(); Simulate.click(buttons[2]); expect(actions.incrementIfOdd.called).to.be.true; }); it('fourth button should call incrementAsync', () => { const { buttons, actions } = setup(); Simulate.click(buttons[3]); expect(actions.incrementAsync.called).to.be.true; }); });
definitions/npm/radium_v0.19.x/test_radium-v0.19.x.js
mkscrg/flow-typed
// @flow import React from 'react'; import Radium from 'radium'; import type { FunctionComponent } from 'radium' type Props1 = { a: number, b: string }; const C1: FunctionComponent<Props1, void> = (props: Props1) => <div>{props.a} {props.b}</div> type Props2 = { a: number, b: string, }; class C2 extends React.Component<void, Props2, void> { render () { return <div>{this.props.a} {this.props.b}</div> } } Radium(<div/>); Radium(<Radium.StyleRoot/>); Radium.keyframes({}); // $ExpectError Radium.keyframes(); // missing object Radium.getState({}, 'ref', ':hover'); // $ExpectError Radium.getState({}, 'ref', ':visible') // invalid property const RC1 = Radium(C1); <RC1 a={1} b="s" />; // $ExpectError <RC1 />; // missing a, b // $ExpectError <RC1 a={1} />; // missing b // $ExpectError <RC1 a="s" b="s" />; // wrong a type const RC2 = Radium(C2); <RC2 a={1} b="s" />; // $ExpectError <RC2 />; // missing a, b // $ExpectError <RC2 a={1} />; // missing b // $ExpectError <RC2 a="s" b="s" />; // wrong a type const ConfiguredRadium = Radium({ userAgent: 'foo' }) const CRC1 = ConfiguredRadium(C1); <CRC1 a={1} b="s" />; // $ExpectError <CRC1 />; // missing a, b // $ExpectError <CRC1 a={1} />; // missing b // $ExpectError <CRC1 a="s" b="s" />; // wrong a type const CRC2 = ConfiguredRadium(C2); <CRC2 a={1} b="s" />; // $ExpectError <CRC2 />; // missing a, b // $ExpectError <CRC2 a={1} />; // missing b // $ExpectError <CRC2 a="s" b="s" />; // wrong a type
src/components/attributes/scatter-plot/local-attributes/GridLines.js
eveafeline/D3-ID3-Naomi
import React, { Component } from 'react'; class GridLines extends Component { constructor(props) { super(props) this.state = { checkbox: false } this.handleCheckbox = this.handleCheckbox.bind(this); this.onSubmit = this.onSubmit.bind(this); } onSubmit(event) { event.preventDefault(); } handleCheckbox(event) { this.setState({ checkbox: !this.state.checkbox }); } render() { let gridLineDisplay = <div className="attr-display"></div> const width = <div className="input-container"> <label> width <input type="number" className="form-control"></input> </label> </div> const color = <div className="input-container"> <label> color <input type="text" className="form-control"></input> </label> </div> if (this.state.checkbox) { gridLineDisplay = <div className="attr-display"> <h6 className="panel-subheaders">X-GridLines</h6> <div className="input-group"> {width} {color} </div> <h6 className="panel-subheaders">Y-Gridlines</h6> <div className="input-group"> {width} {color} </div> </div> } return( <div className="attr-container"> {/* <header className="toolbar toolbar-header attr-header"> <div className="checkbox"> <form onSubmit={this.onSubmit}> <label> <input type="checkbox" onChange={this.handleCheckbox} checked={this.state.checkbox}/> Grid Lines </label> </form> </div> </header> */} <div onClick={this.handleCheckbox} checked={this.state.checkbox}> <h5 className="panel-headers">Grid Lines</h5> </div> {gridLineDisplay} </div> ); } } export default GridLines;
modules/dreamview/frontend/src/components/PNCMonitor/ControlMonitor.js
jinghaomiao/apollo
import React from 'react'; import { inject, observer } from 'mobx-react'; import SETTING from 'store/config/ControlGraph.yml'; import ScatterGraph, { generateScatterGraph } from 'components/PNCMonitor/ScatterGraph'; @inject('store') @observer export default class ControlMonitor extends React.Component { render() { const { lastUpdatedTime, data } = this.props.store.controlData; if (!lastUpdatedTime) { return null; } return ( <div> {generateScatterGraph(SETTING.trajectoryGraph, data.trajectoryGraph, { pose: data.pose, })} {generateScatterGraph(SETTING.speedGraph, data.speedGraph)} {generateScatterGraph(SETTING.accelerationGraph, data.accelerationGraph)} {generateScatterGraph(SETTING.curvatureGraph, data.curvatureGraph)} {generateScatterGraph(SETTING.stationErrorGraph, data.stationErrorGraph)} {generateScatterGraph(SETTING.lateralErrorGraph, data.lateralErrorGraph)} {generateScatterGraph(SETTING.headingErrorGraph, data.headingErrorGraph)} </div> ); } }
src/js/container/ScrollSpy.js
tpucci/jobads-webapp
import React from 'react'; let latestKnownScrollY; let raf; let ticking; let waiting; let endScrollHandle; export default class ScrollSpy extends React.Component { constructor(props) { super(props); this.state = { top: 0, inertia: 0, isAtTop: true }; } componentDidMount() { raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; latestKnownScrollY = window.scrollY; ticking = false; window.addEventListener('scroll', this._handleScroll, false); } componentWillUnmount() { window.removeEventListener('scroll', this._handleScroll); } _handleScroll = () => { latestKnownScrollY = window.scrollY; this._requestTick(); } _requestTick = () => { if(!ticking) { raf(this._requestCalculate); } ticking = true; } _requestCalculate = () => { if (waiting) { return; } waiting = true; // clear previous scheduled endScrollHandle clearTimeout(endScrollHandle); this._calculate(); setTimeout( () => { waiting = false; }, 200); // schedule an extra execution of scroll() after 400ms // in case the scrolling stops in next 200ms endScrollHandle = setTimeout( () => { this._calculate(); }, 400); } _calculate = () => { ticking = false; let top = latestKnownScrollY; let isAtTop = (top == 0); let inertia = this.state.top - top; this.setState({ top, inertia, isAtTop }); } render () { const childrenWithProps = React.Children.map(this.props.children, (child) => React.cloneElement(child, { top: this.state.top, isAtTop: this.state.isAtTop, inertia: this.state.inertia, }) ); return ( <div> {childrenWithProps} </div> ); } }
sub-packs/themes/zealder-default-theme/src/components/Html.js
Zealder/zealder-cms
// @flow // this is the most generic content component that only export content as html import React from 'react'; export default class Html extends React.Component { componentDidMount() { if ($(".as-html form").length) { // since there is form on page, add recaptcha grecaptcha.ready(function() { grecaptcha.execute(reCAPTCHAkey, {action: 'html_form'}).then((token) => { var input = $("<input>").attr("type", "hidden").attr("name", "recaptcha").val(token); $('.as-html form').append($(input)); }); }); } } render() { // default value when content hasn't been added let content = {__html: "This content is not available"}; const {html} = this.props.content.scContent; if (html) { content = {__html: html} } return ( <div dangerouslySetInnerHTML={content} className="as-html" /> ); } }
src/components/Contact/Contact.js
notaurologist/jasonlemoine.com
import React from 'react'; import styles from './contact.css'; const Contact = () => ( <main className={ styles.contact }> <form action="https://formspree.io/site@lemoine.io" method="POST"> <input type="hidden" name="_next" value="http://www.jasonlemoine.com/contact/thanks" /> <input type="text" name="_gotcha" style={ {display:'none'} } /> <input type="text" role="textbox" aria-label="name" name="name" placeholder="Name" tabIndex="1" required /> <input type="email" role="textbox" aria-label="_replyto" name="_replyto" placeholder="Email" tabIndex="2" required /> <textarea aria-label="message" role="textbox" aria-multiline="true" name="message" placeholder="Message" tabIndex="3" required></textarea> <button tabIndex="4">Send</button> </form> </main> ); export default Contact;
src/containers/community/InvitationList.js
Hylozoic/hylo-redux
import React from 'react' import { humanDate } from '../../util/text' import A from '../../components/A' import Avatar from '../../components/Avatar' import { fetchInvitations, sendCommunityInvitation, notify, resendAllCommunityInvitations } from '../../actions' import { FETCH_INVITATIONS } from '../../actions/constants' import cx from 'classnames' import { get, uniqBy } from 'lodash/fp' import { connect } from 'react-redux' const InvitationList = connect((state, { id }) => ({ invitationEditor: get('invitationEditor', state), invitations: state.invitations[id], total: state.totalInvitations[id], pending: state.pending[FETCH_INVITATIONS] }))(props => { const { invitations, pending, total, dispatch, id, invitationEditor } = props const offset = get('length', invitations) || 0 const loadMore = () => !pending && offset < total && dispatch(fetchInvitations(id, offset)) const countText = offset < total ? `showing ${invitations.length} of ${total} invitations, ${invitations.filter(i => i.user).length} used` : `${total} invitations sent, ${invitations.filter(i => i.user).length} used` const { subject, message, moderator } = invitationEditor const resendAll = () => dispatch(resendAllCommunityInvitations(id, {subject, message})) .then(({ error }) => { if (error) { dispatch(notify('There was a problem sending these invitations; please try again later.', {type: 'error'})) } else { dispatch(notify('Your invitations have been queued and will be sent shortly.')) } }) const sendInvitation = email => dispatch(sendCommunityInvitation(id, {subject, message, emails: [email], moderator})) .then(({ error }) => { if (error) { dispatch(notify('There was a problem sending this invitation; please try again later.', {type: 'error'})) } else { dispatch(notify(`Invitation sent to ${email}.`)) } }) return <div className='invitations'> <div className='invitations-header'> <label>Pending Invitations</label> <p className='count'>{countText}</p> <p className='summary'>These are people you have already sent invitations to.</p> <a className='resend-all' onClick={resendAll}>Resend All</a> </div> <div className='person-table'> <table> <thead> <tr> <th>Recipient</th> <th>Used by</th> <th>Time sent</th> <th></th> </tr> </thead> <tbody> {uniqBy('email', (invitations || [])).map((invitation, index) => { let person = invitation.user return <tr key={invitation.id} className={cx({even: index % 2 === 0})}> <td>{invitation.email}</td> {person ? <td className='person'> <Avatar person={person} /> <A to={`/u/${person.id}`}>{person.name}</A> </td> : <td className='unused'>unused</td>} <td>{humanDate(invitation.created_at)}</td> {person ? <td /> : <td><a className='table-button' onClick={() => sendInvitation(invitation.email)}> Resend </a></td> } </tr> })} {offset < total && <tr><td /><td /><td /> <td> <button onClick={loadMore}>Load More</button> </td> </tr>} </tbody> </table> </div> </div> }) export default InvitationList
test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js
timlogemann/create-react-app
import React, { Component } from 'react'; import { bar as bar2 } from './AppUnknownExport'; class App extends Component { componentDidMount() { bar2(); } render() { return <div />; } } export default App;
app/javascript/mastodon/features/ui/components/columns_area.js
WitchesTown/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import { links, getIndex, getLink } from './tabs_bar'; import { Link } from 'react-router-dom'; import BundleContainer from '../containers/bundle_container'; import ColumnLoading from './column_loading'; import DrawerLoading from './drawer_loading'; import BundleColumnError from './bundle_column_error'; import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components'; import detectPassiveEvents from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'FAVOURITES': FavouritedStatuses, 'LIST': ListTimeline, }; const shouldHideFAB = path => path.match(/^\/statuses\//); @component => injectIntl(component, { withRef: true }) export default class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, columns: ImmutablePropTypes.list.isRequired, isModalOpen: PropTypes.bool.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; state = { shouldAnimate: false, } componentWillReceiveProps() { this.setState({ shouldAnimate: false }); } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl'); this.setState({ shouldAnimate: true }); } componentWillUpdate(nextProps) { if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } componentDidUpdate(prevProps) { if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.setState({ shouldAnimate: true }); } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } handleChildrenContentChange() { if (!this.props.singleColumn) { const modifier = this.isRtlLayout ? -1 : 1; this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier); } } handleSwipe = (index) => { this.pendingIndex = index; const nextLinkTranslationId = links[index].props['data-preview-title-id']; const currentLinkSelector = '.tabs-bar__link.active'; const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`; // HACK: Remove the active class from the current link and set it to the next one // React-router does this for us, but too late, feeling laggy. document.querySelector(currentLinkSelector).classList.remove('active'); document.querySelector(nextLinkSelector).classList.add('active'); } handleAnimationEnd = () => { if (typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = (node) => { this.node = node; } renderView = (link, index) => { const columnIndex = getIndex(this.context.router.history.location.pathname); const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] }); const icon = link.props['data-preview-icon']; const view = (index === columnIndex) ? React.cloneElement(this.props.children) : <ColumnLoading title={title} icon={icon} />; return ( <div className='columns-area' key={index}> {view} </div> ); } renderLoading = columnId => () => { return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { columns, children, singleColumn, isModalOpen } = this.props; const { shouldAnimate } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); this.pendingIndex = null; if (singleColumn) { const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button'><i className='fa fa-pencil' /></Link>; return columnIndex !== -1 ? [ <ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}> {links.map(this.renderView)} </ReactSwipeableViews>, floatingActionButton, ] : [ <div className='columns-area'>{children}</div>, floatingActionButton, ]; } return ( <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}> {columns.map(column => { const params = column.get('params', null) === null ? null : column.get('params').toJS(); return ( <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}> {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />} </BundleContainer> ); })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
modules/IndexLink.js
upraised/react-router
import React from 'react' import Link from './Link' const IndexLink = React.createClass({ render() { return <Link {...this.props} onlyActiveOnIndex={true} /> } }) export default IndexLink
src/js/components/icons/base/Power.js
odedre/grommet-final
/** * @description Power SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M16,4 C19.3637732,5.43018182 22,8.98935065 22,13 C22,18.6008831 17.5273457,23 12,23 C6.47265429,23 2,18.6008831 2,13 C2,8.98935065 4.63622679,5.43018182 8,4 M12,1 L12,11"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-power`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'power'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M16,4 C19.3637732,5.43018182 22,8.98935065 22,13 C22,18.6008831 17.5273457,23 12,23 C6.47265429,23 2,18.6008831 2,13 C2,8.98935065 4.63622679,5.43018182 8,4 M12,1 L12,11"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Power'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/Transition.js
cesarandreu/react-overlays
import React from 'react'; import transitionInfo from 'dom-helpers/transition/properties'; import addEventListener from 'dom-helpers/events/on'; import classnames from 'classnames'; let transitionEndEvent = transitionInfo.end; export const UNMOUNTED = 0; export const EXITED = 1; export const ENTERING = 2; export const ENTERED = 3; export const EXITING = 4; /** * The Transition component lets you define and run css transitions with a simple declarative api. * It works similar to React's own [CSSTransitionGroup](http://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup) * but is specifically optimized for transitioning a single child "in" or "out". * * You don't even need to use class based css transitions if you don't want to (but it is easiest). * The extensive set of lifecyle callbacks means you have control over * the transitioning now at each step of the way. */ class Transition extends React.Component { constructor(props, context) { super(props, context); let initialStatus; if (props.in) { // Start enter transition in componentDidMount. initialStatus = props.transitionAppear ? EXITED : ENTERED; } else { initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED; } this.state = {status: initialStatus}; this.nextCallback = null; } componentDidMount() { if (this.props.transitionAppear && this.props.in) { this.performEnter(this.props); } } componentWillReceiveProps(nextProps) { const status = this.state.status; if (nextProps.in) { if (status === EXITING) { this.performEnter(nextProps); } else if (this.props.unmountOnExit) { if (status === UNMOUNTED) { // Start enter transition in componentDidUpdate. this.setState({status: EXITED}); } } else if (status === EXITED) { this.performEnter(nextProps); } // Otherwise we're already entering or entered. } else { if (status === ENTERING || status === ENTERED) { this.performExit(nextProps); } // Otherwise we're already exited or exiting. } } componentDidUpdate() { if (this.props.unmountOnExit && this.state.status === EXITED) { // EXITED is always a transitional state to either ENTERING or UNMOUNTED // when using unmountOnExit. if (this.props.in) { this.performEnter(this.props); } else { this.setState({status: UNMOUNTED}); } } } componentWillUnmount() { this.cancelNextCallback(); } performEnter(props) { this.cancelNextCallback(); const node = React.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onEnter(node); this.safeSetState({status: ENTERING}, () => { this.props.onEntering(node); this.onTransitionEnd(node, () => { this.safeSetState({status: ENTERED}, () => { this.props.onEntered(node); }); }); }); } performExit(props) { this.cancelNextCallback(); const node = React.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onExit(node); this.safeSetState({status: EXITING}, () => { this.props.onExiting(node); this.onTransitionEnd(node, () => { this.safeSetState({status: EXITED}, () => { this.props.onExited(node); }); }); }); } cancelNextCallback() { if (this.nextCallback !== null) { this.nextCallback.cancel(); this.nextCallback = null; } } safeSetState(nextState, callback) { // This shouldn't be necessary, but there are weird race conditions with // setState callbacks and unmounting in testing, so always make sure that // we can cancel any pending setState callbacks after we unmount. this.setState(nextState, this.setNextCallback(callback)); } setNextCallback(callback) { let active = true; this.nextCallback = (event) => { if (active) { active = false; this.nextCallback = null; callback(event); } }; this.nextCallback.cancel = () => { active = false; }; return this.nextCallback; } onTransitionEnd(node, handler) { this.setNextCallback(handler); if (node) { addEventListener(node, transitionEndEvent, this.nextCallback); setTimeout(this.nextCallback, this.props.timeout); } else { setTimeout(this.nextCallback, 0); } } render() { const status = this.state.status; if (status === UNMOUNTED) { return null; } const {children, className, ...childProps} = this.props; Object.keys(Transition.propTypes).forEach(key => delete childProps[key]); let transitionClassName; if (status === EXITED) { transitionClassName = this.props.exitedClassName; } else if (status === ENTERING) { transitionClassName = this.props.enteringClassName; } else if (status === ENTERED) { transitionClassName = this.props.enteredClassName; } else if (status === EXITING) { transitionClassName = this.props.exitingClassName; } const child = React.Children.only(children); return React.cloneElement( child, { ...childProps, className: classnames( child.props.className, className, transitionClassName ) } ); } } Transition.propTypes = { /** * Show the component; triggers the enter or exit animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is not shown */ unmountOnExit: React.PropTypes.bool, /** * Run the enter animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * A Timeout for the animation, in milliseconds, to ensure that a node doesn't * transition indefinately if the browser transitionEnd events are * canceled or interrupted. * * By default this is set to a high number (5 seconds) as a failsafe. You should consider * setting this to the duration of your animation (or a bit above it). */ timeout: React.PropTypes.number, /** * CSS class or classes applied when the component is exited */ exitedClassName: React.PropTypes.string, /** * CSS class or classes applied while the component is exiting */ exitingClassName: React.PropTypes.string, /** * CSS class or classes applied when the component is entered */ enteredClassName: React.PropTypes.string, /** * CSS class or classes applied while the component is entering */ enteringClassName: React.PropTypes.string, /** * Callback fired before the "entering" classes are applied */ onEnter: React.PropTypes.func, /** * Callback fired after the "entering" classes are applied */ onEntering: React.PropTypes.func, /** * Callback fired after the "enter" classes are applied */ onEntered: React.PropTypes.func, /** * Callback fired before the "exiting" classes are applied */ onExit: React.PropTypes.func, /** * Callback fired after the "exiting" classes are applied */ onExiting: React.PropTypes.func, /** * Callback fired after the "exited" classes are applied */ onExited: React.PropTypes.func }; // Name the function so it is clearer in the documentation function noop() {} Transition.displayName = 'Transition'; Transition.defaultProps = { in: false, unmountOnExit: false, transitionAppear: false, timeout: 5000, onEnter: noop, onEntering: noop, onEntered: noop, onExit: noop, onExiting: noop, onExited: noop }; export default Transition;