path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/run.js
bluebill1049/cart
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/app/contentItem.js
approximata/theUltimateWeddingPage
import React from 'react' import PropTypes from 'prop-types' import TableItem from './tableItems' const ContentItem = ({ item }) => { let rows = item.rows let table = [] table = rows.map((itemElem, index) => (<TableItem item={itemElem} key={index}/>)) return ( <section className={item.title}> <table className='table table-border'><tbody>{table}</tbody></table> <div name={ item.subTitle1 } className={item.title + ' subTitle1' + ' container'}> <h2><a href={item.link}><span className={ item.icon }></span></a>{item.subTitle1}</h2> <p>{item.content1}</p> </div> <div name={ item.subTitle2 } className={item.title + ' subTitle2' + ' container'}> <h2>{item.subTitle2}</h2> <p>{item.content2}</p> </div> </section> ) } ContentItem.propTypes = { item: PropTypes.object } export default ContentItem
examples/js/advance/insert-type-table.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const jobs = []; const jobTypes = [ 'A', 'B', 'C', 'D' ]; function addJobs(quantity) { const startId = jobs.length; for (let i = 0; i < quantity; i++) { const id = startId + i; jobs.push({ id: id, name: 'Item name ' + id, type: 'B', active: i % 2 === 0 ? 'Y' : 'N' }); } } addJobs(5); export default class DataInsertTypeTable extends React.Component { render() { return ( <BootstrapTable data={ jobs } insertRow={ true }> <TableHeaderColumn dataField='id' isKey={ true }>Job ID</TableHeaderColumn> <TableHeaderColumn dataField='name' editable={ { type: 'textarea' } }>Job Name</TableHeaderColumn> <TableHeaderColumn dataField='type' editable={ { type: 'select', options: { values: jobTypes } } }>Job Type</TableHeaderColumn> <TableHeaderColumn dataField='active' editable={ { type: 'checkbox', options: { values: 'Y:N' } } }>Active</TableHeaderColumn> </BootstrapTable> ); } }
src/components/atoms/Dialog/DialogActions.js
ygoto3/artwork-manager
// @flow import React, { Component } from 'react'; import { Button } from '../../atoms/Button'; export type DialogAction = { label: string; onClick: Function; }; export type DialogActionsProps = { actions: DialogAction[]; onClose: Function; } export class DialogActions extends Component<*, DialogActionsProps, *> { render() { const { actions, onClose } = this.props; return ( <div> {actions.map((a, i) => ( <Button key={i} onClick={a.onClick}>{a.label}</Button> ))} <Button onClick={onClose}>Close</Button> </div> ); } } Object.assign(DialogActions, { defaultProps: { actions: [] }, });
src/index.js
plus-n-boots/plus-n-boots.github.io
import React from 'react' import AppWrapper from './containers/AppWrapper' import 'material-design-lite/material.css' React.render( <AppWrapper />, document.querySelector('wrapper') )
src/components/Table.js
cardotrejos/calculator
import React from 'react'; export default ({headings, rows, totals, className, style})=> ( <table className={className} style={style}> <thead> <tr> {headings.map((d,i)=><th key={i}>{d}</th>)} </tr> </thead> <tbody> {rows.map((row,index)=>( <tr key={index}> {row.map((d,i)=><td key={i}>{d.toLocaleString()}</td>)} </tr>) ) } </tbody> <tfoot> <tr> {totals.map((d,i)=><td key={i}>{d.toLocaleString()}</td>)} </tr> </tfoot> </table> );
src/js/components/questions/AcceptedAnswersImportance.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import TextRadios from './../ui/TextRadios'; import translate from '../../i18n/Translate'; import Framework7Service from '../../services/Framework7Service'; import SelectInline from "../ui/SelectInline/SelectInline"; @translate('AcceptedAnswersImportance') export default class AcceptedAnswersImportance extends Component { static propTypes = { irrelevant : PropTypes.bool.isRequired, answeredAndAccepted: PropTypes.bool, onClickHandler : PropTypes.func.isRequired, // Injected by @translate: strings : PropTypes.object }; constructor(props) { super(props); this.handleOnImportanceClick = this.handleOnImportanceClick.bind(this); this.handleSelectInlineOnImportanceClick = this.handleSelectInlineOnImportanceClick.bind(this); this.showNotCompleteModal = this.showNotCompleteModal.bind(this); this.state = { importance: null }; } handleOnImportanceClick(key) { if (!this.props.answeredAndAccepted) { this.showNotCompleteModal(); return; } this.setState({ importance: key }); this.props.onClickHandler(key); } handleSelectInlineOnImportanceClick(key) { if (!this.props.answeredAndAccepted) { this.showNotCompleteModal(); return; } this.setState({ importance: key[0] }); this.props.onClickHandler(key[0]); } showNotCompleteModal() { const {strings} = this.props; Framework7Service.nekunoApp().alert(strings.alert); }; render() { const {answeredAndAccepted, strings} = this.props; const className = answeredAndAccepted ? 'accepted-answers-importance' : 'accepted-answers-importance disabled'; const options = [ { id: "few", text: strings.few }, { id: "normal", text: strings.normal }, { id: "aLot", text: strings.aLot } ]; return ( <div className={className}> {this.props.irrelevant ? <SelectInline options={[{id: 'irrelevant', text: strings.irrelevant}]} onClickHandler={this.handleSelectInlineOnImportanceClick} value={this.state.importance} /> : <SelectInline options={options} onClickHandler={this.handleSelectInlineOnImportanceClick} defaultOption={this.state.importance} /> } </div> ); } } AcceptedAnswersImportance.defaultProps = { strings: { title : 'Do you mind the user response?', irrelevant: 'Irrelevant', few : 'Little bit', normal : 'Normal', aLot : 'A lot', alert : 'Mark your answer and one or more options in the second column to indicate what would you like to answer another user' } };
src/client.js
trungtin/react-redux-universal-hot-example
/** * 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 createLocation from 'history/lib/createLocation'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import universalRouter from './helpers/universalRouter'; import io from 'socket.io-client'; const history = createHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(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 location = createLocation(document.location.pathname, document.location.search); const render = (loc, hist, str, preload) => { return universalRouter(loc, hist, str, preload) .then(({component}) => { ReactDOM.render(component, dest); if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); ReactDOM.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } }, (error) => { console.error(error); }); }; history.listen(() => {}); history.listenBefore((loc, callback) => { render(loc, history, store, true) .then((callback)); }); render(location, history, store); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.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.'); } }
scripts/Notepad.js
sarahedkins/calculator-app
import React, { Component } from 'react'; export default class Notepad extends Component { constructor(props) { super(props); const notepad = this.getNotepad(); const initialNote = 'Write your notes here - We\'ll save it for offline!'; this.state = { note: notepad || initialNote, }; } setNotepad = (val) => { localStorage.notepad = val; }; getNotepad = () => localStorage.notepad; saveText = (e) => { e.preventDefault(); this.setNotepad(this.state.note); } updateTextArea = (e) => { this.setState({ note: e.target.value, }); } render() { return ( <div className="border"> <h2 className="header"> Notepad </h2> <br /> <form onSubmit={this.saveText}> <label htmlFor="notepad-textbox"> <input id="notepad-textbox" type="text" value={this.state.note} onChange={this.updateTextArea} /> </label> <input type="submit" value="Submit" /> </form> </div> ); } }
src/charts/row-chart.js
WaldoJeffers/react-dc
import React from 'react' import dc from 'dc' import BaseChart from './base-chart' import baseMixin from '../mixins/base-mixin' import marginMixin from '../mixins/margin-mixin' import capMixin from '../mixins/cap-mixin' import colorMixin from '../mixins/color-mixin' import rowMixin from '../mixins/row-mixin' const {any, bool, number, oneOfType} = React.PropTypes @rowMixin @colorMixin @capMixin @marginMixin @baseMixin export default class RowChart extends BaseChart{ static displayName = 'RowChart' componentDidMount(){ this.chart = dc.rowChart(this.chart) this.configure() this.chart.render() } }
src/js/ui/components/settings/backupFile.js
hiddentao/heartnotes
import _ from 'lodash'; import React from 'react'; import moment from 'moment'; import ProgressButton from '../progressButton'; import DateFormat from '../date'; import { connectRedux } from '../../helpers/decorators'; var Component = React.createClass({ render: function() { let { diary } = this.props.data; let { diaryMgr } = diary; let lastBackupTime = moment(diaryMgr.backupLastTime); lastBackupTime = (lastBackupTime.valueOf()) ? ( <DateFormat date={diaryMgr.backupLastTime} format="MMMM DD, YYYY - HH:mm:ss" /> ) : ( <span>Never</span> ) let btnAttrs = { defaultProgressMsg: 'Making backup...', progressProps: { centered: false }, checkVar: diary.makingBackup, onClick: this._makeBackup, }; return ( <div className="backup-file"> <h2>Backup</h2> <p className="last"> <label>Last backup:</label> {lastBackupTime} </p> <ProgressButton {...btnAttrs}>Create backup</ProgressButton> </div> ); }, _makeBackup: function() { this.props.actions.makeBackup(); }, }); module.exports = connectRedux([ 'makeBackup', ])(Component);
components/HomePage.js
arpith/react-router-example
import React from 'react'; class HomePage extends React.Component { render() { return ( <div> <h1>Welcome to this react router example!</h1> <p>You can read about it <a href='https://medium.com/@arpith/using-react-router-1f96209fe557#.92v3xhq7l'>here</a></p> <p>The code is <a href='https://github.com/arpith/react-router-example'>on Github</a></p> </div> ); } } export default HomePage;
src/components/reports/report-margin.js
Xabadu/VendOS
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import Moment from 'moment'; import Calendar from 'react-input-calendar'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import Select from 'react-select'; import { getMargins, getList } from '../../actions/index'; import MarginCards from '../common/margin-cards'; class MarginReport extends Component { constructor(props) { super(props); this.filterMargin = this.filterMargin.bind(this); this.state = { from: Moment().format('YYYY-MM-DD') + 'T04:30:00', until: Moment().format('YYYY-MM-DD') + 'T23:59:59', product: '', store: '' }; } componentWillMount() { this.props.getMargins({ dateFrom: this.state.from, dateUntil: this.state.until, product: this.state.product, store: this.state.store } ); this.props.getList('products'); this.props.getList('stores'); } filterMargin() { this.props.getMargins({ dateFrom: this.state.from, dateUntil: this.state.until, product: this.state.product, store: this.state.store } ); } render() { return ( <div> <div className="page-breadcrumb"> <ol className="breadcrumb container"> <li><Link to='/'>Inicio</Link></li> <li><a href="#">Reportes</a></li> <li className="active">Margen</li> </ol> </div> <div className="page-title"> <div className="container"> <h3>Margen</h3> </div> </div> <div id="main-wrapper" className="container"> <div className="row"> <div className="col-md-4"> <div className="panel panel-white"> <div className="panel-body"> <div className="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div className="btn-group" role="group" aria-label="First group"> <button onClick={() => { this.setState({ from: Moment().subtract(7, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default">&Uacute;ltima semana</button> <button onClick={() => { this.setState({ from: Moment().subtract(1, 'month').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default">&Uacute;ltimo mes</button> </div> <div className="btn-group" role="group" aria-label="Second group"> <button onClick={() => { this.setState({ from: Moment().format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default">Hoy</button> <button onClick={() => { this.setState({ from: Moment().subtract(1, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(1, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default">Ayer</button> <button onClick={() => { this.setState({ from: Moment().subtract(2, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(2, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default cap">{Moment().locale('es').subtract(2, 'days').format('dddd')}</button> <button onClick={() => { this.setState({ from: Moment().subtract(3, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(3, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default cap">{Moment().locale('es').subtract(3, 'days').format('dddd')}</button> <button onClick={() => { this.setState({ from: Moment().subtract(4, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(4, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default cap">{Moment().locale('es').subtract(4, 'days').format('dddd')}</button> <button onClick={() => { this.setState({ from: Moment().subtract(5, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(5, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default cap">{Moment().locale('es').subtract(5, 'days').format('dddd')}</button> <button onClick={() => { this.setState({ from: Moment().subtract(6, 'days').format('YYYY-MM-DD')+ "T04:30:00.000Z", until: Moment().subtract(6, 'days').format('YYYY-MM-DD')+ "T23:59:59.000Z" }, function() { this.filterMargin(); }); }} type="button" className="btn btn-default cap">{Moment().locale('es').subtract(6, 'days').format('dddd')}</button> </div> </div> <form className="form-inline m-t-lg"> <div className="form-group"> <label className="sr-only" for="exampleInputEmail2">Desde</label> <Calendar format='DD/MM/YYYY' date={this.state.from} maxDate={new Date()} computableFormat='YYYY-MM-DDT04:30:00.000Z' onChange={date => {this.setState({from: date})}} closeOnSelect={true} placeholder='Desde' openOnInputFocus={true} hideIcon={true} todayText='Hoy' /> </div> <div className="filter-el form-group"> <label className="sr-only" for="exampleInputPassword2">Hasta</label> <Calendar format='DD/MM/YYYY' date={this.state.until} maxDate={new Date()} computableFormat='YYYY-MM-DDT23:59:00.000Z' onChange={date => {this.setState({until: date})}} closeOnSelect={true} placeholder='Hasta' openOnInputFocus={true} hideIcon={true} todayText='Hoy' /> </div> <button onClick={(e) => { e.preventDefault(); this.filterMargin(); } } type="submit" className="filter-el btn btn-info">Buscar por rango</button> </form> </div> </div> </div> <div className="col-md-3"> <div className="panel panel-white"> <h4 className="filter-title">Filtrar por tienda</h4> <div className="panel-body"> <form className="form-inline m-t-lg"> <div className="form-group"> <Select name="select-stores" value={this.state.store} clearable={false} className={'filter-sel'} placeholder={'Filtrar por tienda...'} noResultsText={'No hay resultados'} options={this.props.storesList} onChange={(val) => this.setState({ store: val.value })} /> </div> <button onClick={(e) => { e.preventDefault(); this.filterMargin(); } } type="submit" className="filter-el btn btn-info">Filtrar</button> </form> </div> </div> </div> <div className="col-md-3"> <div className="panel panel-white"> <h4 className="filter-title">Filtrar por producto</h4> <div className="panel-body"> <form className="form-inline m-t-lg"> <div className="form-group"> <Select name="select-products" value={this.state.product} clearable={false} className={'filter-sel'} placeholder={'Filtrar por producto...'} noResultsText={'No hay resultados'} options={this.props.productsList} onChange={(val) => this.setState({ product: val.value })} /> </div> <button onClick={(e) => { e.preventDefault(); this.filterMargin(); } } type="submit" className="filter-el btn btn-info">Filtrar</button> </form> </div> </div> </div> </div> <MarginCards avgMargin={this.props.avgMargin} bestMargin={this.props.bestMargin} worstMargin={this.props.worstMargin} profit={this.props.profit} totalSales={this.props.totalSales} /> </div> </div> ); } } function mapStateToProps(state) { return { productsList: state.reports.productsList, storesList: state.reports.storesList, avgMargin: state.reports.avgMargin, avgPercentage: state.reports.avgPercentage, bestMargin: state.reports.bestMargin, bestPercentage: state.reports.bestPercentage, worstMargin: state.reports.worstMargin, worstPercentage: state.reports.worstPercentage, profit: state.reports.profit, totalSales: state.reports.totalSales } } export default connect(mapStateToProps, { getMargins, getList })(MarginReport);
src/components/header.js
paulckennedy/KennedyChemistryRocks
import React from 'react'; export default (props) => { return ( <div> <header className="hg_header"> <img src = {require('../img/1_Primary_logo_on_transparent_422x59.png')} /> </header> </div> ); }
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Navbar.js
JamieMason/npm-cache-benchmark
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'; // TODO: Remove this pragma once we upgrade eslint-config-airbnb. /* eslint-disable react/no-multi-comp */ import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import elementType from 'react-prop-types/lib/elementType'; import uncontrollable from 'uncontrollable'; import Grid from './Grid'; import NavbarBrand from './NavbarBrand'; import NavbarCollapse from './NavbarCollapse'; import NavbarHeader from './NavbarHeader'; import NavbarToggle from './NavbarToggle'; import { bsClass as setBsClass, bsStyles, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import { Style } from './utils/StyleConfig'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Create a fixed navbar along the top of the screen, that scrolls with the * page */ fixedTop: PropTypes.bool, /** * Create a fixed navbar along the bottom of the screen, that scrolls with * the page */ fixedBottom: PropTypes.bool, /** * Create a full-width navbar that scrolls away with the page */ staticTop: PropTypes.bool, /** * An alternative dark visual style for the Navbar */ inverse: PropTypes.bool, /** * Allow the Navbar to fluidly adjust to the page or container width, instead * of at the predefined screen breakpoints */ fluid: PropTypes.bool, /** * Set a custom element for this component. */ componentClass: elementType, /** * A callback fired when the `<Navbar>` body collapses or expands. Fired when * a `<Navbar.Toggle>` is clicked and called with the new `navExpanded` * boolean value. * * @controllable navExpanded */ onToggle: PropTypes.func, /** * A callback fired when a descendant of a child `<Nav>` is selected. Should * be used to execute complex closing or other miscellaneous actions desired * after selecting a descendant of `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` * descendants exist. The callback is called with an eventKey, which is a * prop from the selected `<Nav>` descendant, and an event. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * For basic closing behavior after all `<Nav>` descendant onSelect events in * mobile viewports, try using collapseOnSelect. * * Note: If you are manually closing the navbar using this `OnSelect` prop, * ensure that you are setting `expanded` to false and not *toggling* between * true and false. */ onSelect: PropTypes.func, /** * Sets `expanded` to `false` after the onSelect event of a descendant of a * child `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` descendants exist. * * The onSelect callback should be used instead for more complex operations * that need to be executed after the `select` event of `<Nav>` descendants. */ collapseOnSelect: PropTypes.bool, /** * Explicitly set the visiblity of the navbar body * * @controllable onToggle */ expanded: PropTypes.bool, role: PropTypes.string }; var defaultProps = { componentClass: 'nav', fixedTop: false, fixedBottom: false, staticTop: false, inverse: false, fluid: false, collapseOnSelect: false }; var childContextTypes = { $bs_navbar: PropTypes.shape({ bsClass: PropTypes.string, expanded: PropTypes.bool, onToggle: PropTypes.func.isRequired, onSelect: PropTypes.func }) }; var Navbar = function (_React$Component) { _inherits(Navbar, _React$Component); function Navbar(props, context) { _classCallCheck(this, Navbar); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleToggle = _this.handleToggle.bind(_this); _this.handleCollapse = _this.handleCollapse.bind(_this); return _this; } Navbar.prototype.getChildContext = function getChildContext() { var _props = this.props, bsClass = _props.bsClass, expanded = _props.expanded, onSelect = _props.onSelect, collapseOnSelect = _props.collapseOnSelect; return { $bs_navbar: { bsClass: bsClass, expanded: expanded, onToggle: this.handleToggle, onSelect: createChainedFunction(onSelect, collapseOnSelect ? this.handleCollapse : null) } }; }; Navbar.prototype.handleCollapse = function handleCollapse() { var _props2 = this.props, onToggle = _props2.onToggle, expanded = _props2.expanded; if (expanded) { onToggle(false); } }; Navbar.prototype.handleToggle = function handleToggle() { var _props3 = this.props, onToggle = _props3.onToggle, expanded = _props3.expanded; onToggle(!expanded); }; Navbar.prototype.render = function render() { var _extends2; var _props4 = this.props, Component = _props4.componentClass, fixedTop = _props4.fixedTop, fixedBottom = _props4.fixedBottom, staticTop = _props4.staticTop, inverse = _props4.inverse, fluid = _props4.fluid, className = _props4.className, children = _props4.children, props = _objectWithoutProperties(_props4, ['componentClass', 'fixedTop', 'fixedBottom', 'staticTop', 'inverse', 'fluid', 'className', 'children']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['expanded', 'onToggle', 'onSelect', 'collapseOnSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; // will result in some false positives but that seems better // than false negatives. strict `undefined` check allows explicit // "nulling" of the role if the user really doesn't want one if (elementProps.role === undefined && Component !== 'nav') { elementProps.role = 'navigation'; } if (inverse) { bsProps.bsStyle = Style.INVERSE; } var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'fixed-top')] = fixedTop, _extends2[prefix(bsProps, 'fixed-bottom')] = fixedBottom, _extends2[prefix(bsProps, 'static-top')] = staticTop, _extends2)); return React.createElement( Component, _extends({}, elementProps, { className: classNames(className, classes) }), React.createElement( Grid, { fluid: fluid }, children ) ); }; return Navbar; }(React.Component); Navbar.propTypes = propTypes; Navbar.defaultProps = defaultProps; Navbar.childContextTypes = childContextTypes; setBsClass('navbar', Navbar); var UncontrollableNavbar = uncontrollable(Navbar, { expanded: 'onToggle' }); function createSimpleWrapper(tag, suffix, displayName) { var Wrapper = function Wrapper(_ref, _ref2) { var _ref2$$bs_navbar = _ref2.$bs_navbar, navbarProps = _ref2$$bs_navbar === undefined ? { bsClass: 'navbar' } : _ref2$$bs_navbar; var Component = _ref.componentClass, className = _ref.className, pullRight = _ref.pullRight, pullLeft = _ref.pullLeft, props = _objectWithoutProperties(_ref, ['componentClass', 'className', 'pullRight', 'pullLeft']); return React.createElement(Component, _extends({}, props, { className: classNames(className, prefix(navbarProps, suffix), pullRight && prefix(navbarProps, 'right'), pullLeft && prefix(navbarProps, 'left')) })); }; Wrapper.displayName = displayName; Wrapper.propTypes = { componentClass: elementType, pullRight: PropTypes.bool, pullLeft: PropTypes.bool }; Wrapper.defaultProps = { componentClass: tag, pullRight: false, pullLeft: false }; Wrapper.contextTypes = { $bs_navbar: PropTypes.shape({ bsClass: PropTypes.string }) }; return Wrapper; } UncontrollableNavbar.Brand = NavbarBrand; UncontrollableNavbar.Header = NavbarHeader; UncontrollableNavbar.Toggle = NavbarToggle; UncontrollableNavbar.Collapse = NavbarCollapse; UncontrollableNavbar.Form = createSimpleWrapper('div', 'form', 'NavbarForm'); UncontrollableNavbar.Text = createSimpleWrapper('p', 'text', 'NavbarText'); UncontrollableNavbar.Link = createSimpleWrapper('a', 'link', 'NavbarLink'); // Set bsStyles here so they can be overridden. export default bsStyles([Style.DEFAULT, Style.INVERSE], Style.DEFAULT, UncontrollableNavbar);
client/src/Layout.js
MattMcFarland/reactathon
import React from 'react'; import { Link } from 'react-router'; import { Navbar, Nav, MenuItem, Modal, Button, NavDropdown } from 'react-bootstrap'; import { SignupForm, LoginForm } from './components'; import { Logo } from './components/partials/Elements'; import { AppActions } from './actions/AppActions'; import { AppStore } from './stores/AppStore'; import NotificationSystem from 'react-notification-system'; const Content = ({children}) => ( <div>{children}</div> ); export class Layout extends React.Component { constructor() { super(); this.state = { ...AppStore.getState() }; this._notificationSystem = null; this.onChange = this.onChange.bind(this); } componentDidMount() { AppStore.listen(this.onChange); this._notificationSystem = this.refs.notificationSystem; } componentWillUnmount() { AppStore.unlisten(this.onChange); } addNotification = (queue) => { let message = queue.slice(0, 1); this._notificationSystem.addNotification(message[0]); }; onChange(state) { if (state.queue && state.queue.length) { setTimeout(this.addNotification(state.queue), 100); } this.setState(state); } render() { var Menu; var name = this.props.location.pathname; let { showSignupModal, showLoginModal } = this.state; let onShowSignupForm = () => (AppActions.showSignupModal()); let onShowLoginForm = () => (AppActions.showLoginModal()); let onHideSignupForm = () => (AppActions.hideSignupModal()); let onHideLoginForm = () => (AppActions.hideLoginModal()); let logout = (e) => { e.preventDefault(); AppActions.logout(); }; let gotoDashboard = (e) => { e.preventDefault(); this.props.history.push('/dashboard'); }; let gotoAddNewArticle = (e) => { e.preventDefault(); this.props.history.push('/add-article'); }; if (this.state.user) { Menu = ({}) => ( <Nav pullRight style={{marginTop: '5px'}}> <NavDropdown eventKey={2} title='Create' id='create-dropdown'> <MenuItem onClick={gotoAddNewArticle} eventKey={2.1}> Add New Article </MenuItem> </NavDropdown> <NavDropdown eventKey={3} title='Account' id='user-dropdown'> <MenuItem onClick={gotoDashboard} eventKey={3.1}> Dashboard </MenuItem> <MenuItem divider /> <MenuItem onClick={logout} eventKey={3.2}>Logout</MenuItem> </NavDropdown> </Nav> ); } else { Menu = ({}) => ( <Nav pullRight style={{marginTop: '5px'}}> <Button bsStyle='link' onClick={onShowSignupForm}> Create Account </Button> <Button bsStyle='link' onClick={onShowLoginForm}> Login </Button> </Nav> ); } return ( <section> <Navbar inverse> <Navbar.Header> <Navbar.Brand> <Link style={{paddingTop: '21px'}} to='/'> <Logo /> </Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <Navbar.Text> <Link activeClassName='active' className='nav-item nav-link btn btn-link' to='/page/about'>About</Link> </Navbar.Text> <Navbar.Text> <Link activeClassName='active' className='nav-item nav-link btn btn-link' to='/articles'>Articles</Link> </Navbar.Text> </Nav> <Menu/> </Navbar.Collapse> </Navbar> <section className='container'> <Content key={name}> {this.props.children} </Content> </section> {showSignupModal ? <Modal show={showSignupModal} onHide={onHideSignupForm}> <Modal.Header closeButton> <Modal.Title>Signup</Modal.Title> </Modal.Header> <Modal.Body> <SignupForm /> </Modal.Body> <Modal.Footer> <Button onClick={onHideSignupForm}> Cancel </Button> </Modal.Footer> </Modal> : ''} {showLoginModal ? <Modal show={showLoginModal} onHide={onHideLoginForm}> <Modal.Header closeButton> <Modal.Title>Login</Modal.Title> </Modal.Header> <Modal.Body> <LoginForm /> </Modal.Body> <Modal.Footer> <Button onClick={onHideLoginForm}> Cancel </Button> </Modal.Footer> </Modal> : ''} <NotificationSystem ref='notificationSystem' /> </section> ); } } Layout.contextTypes = { router: React.PropTypes.object.isRequired };
app/comps/people/Person.js
efvincent/flux-pack-reflux
import React from 'react'; import Reflux from 'reflux'; import PersonStore from '../../stores/PersonStore'; import {PersonActions} from '../../actions'; import Glyph from '../Glyph'; export default React.createClass({ displayName: 'Person', mixins: [Reflux.connect(PersonStore, 'person')], contextTypes: { router: React.PropTypes.func }, componentWillMount() { let router = this.context.router; let id = router.getCurrentParams().id; if (id !== undefined) { PersonActions.loadPersonWithId(id); } }, changePersonProps() { PersonActions.setProps({ fname: this.refs.fn.getDOMNode().value, lname: this.refs.ln.getDOMNode().value }); }, save() { if (this.state.person.isValid()) { PersonActions.savePerson(); this.context.router.transitionTo('people'); } }, render() { return ( <form className='row'> <div className='col-xs-5'> <h1>Person</h1> <div className='form-group'> <label>First Name</label> <input type='text' ref='fn' className='form-control' placeholder='First Name' onChange={this.changePersonProps} defaultValue={this.state.person.fname} /> </div> <div className='form-group'> <label>Last Name</label> <input type='text' ref='ln' className='form-control' placeholder='Last Name' onChange={this.changePersonProps} defaultValue={this.state.person.lname} /> </div> <button className='btn btn-primary' onClick={this.save}><Glyph icon='floppy-disk'/> Save</button> </div> </form> ); } });
actor-apps/app-web/src/app/components/common/Image.react.js
luoxiaoshenghustedu/actor-platform
import React from 'react'; import classnames from 'classnames'; import Lightbox from 'jsonlylightbox'; // lightbox init const lightbox = new Lightbox(); const lightboxOptions = { animation: false, controlClose: '<i class="material-icons">close</i>' }; lightbox.load(lightboxOptions); let cache = {}; class Image extends React.Component { static propTypes = { content: React.PropTypes.object.isRequired, className: React.PropTypes.string, loadedClassName: React.PropTypes.string }; constructor(props) { super(props); this.state = { isImageLoaded: this.isCached() }; } openLightBox() { lightbox.open(this.props.content.fileUrl, 'message'); } onLoad() { this.setCached(); if (!this.state.isImageLoaded) { this.setState({isImageLoaded: true}); } } isCached() { return (cache[this.props.content.fileUrl] === true); } setCached() { cache[this.props.content.fileUrl] = true; } render() { const { content, className, loadedClassName } = this.props; const { isImageLoaded } = this.state; const k = content.w / 300; const styles = { width: Math.round(content.w / k), height: Math.round(content.h / k) }; let original = null, preview = null, preloader = null; if (content.fileUrl) { original = ( <img className="photo photo--original" height={content.h} onClick={this.openLightBox.bind(this)} onLoad={this.onLoad.bind(this)} src={content.fileUrl} width={content.w}/> ); } if (!this.isCached()) { preview = <img className="photo photo--preview" src={content.preview}/>; if (content.isUploading === true || isImageLoaded === false) { preloader = <div className="preloader"><div/><div/><div/><div/><div/></div>; } } const imageClassName = isImageLoaded ? classnames(className, loadedClassName) : className; return ( <div className={imageClassName} style={styles}> {preview} {original} {preloader} <svg dangerouslySetInnerHTML={{__html: '<filter id="blur-effect"><feGaussianBlur stdDeviation="3"/></filter>'}}></svg> </div> ); } } export default Image;
src/containers/Login/Login.js
bertho-zero/react-redux-universal-hot-example
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import LoginForm from 'components/LoginForm/LoginForm'; import FacebookLogin from 'components/FacebookLogin/FacebookLogin'; import * as authActions from 'redux/modules/auth'; import * as notifActions from 'redux/modules/notifs'; @connect( state => ({ user: state.auth.user }), { ...notifActions, ...authActions } ) @withRouter class Login extends Component { static propTypes = { user: PropTypes.shape({ email: PropTypes.string }), login: PropTypes.func.isRequired, logout: PropTypes.func.isRequired, notifSend: PropTypes.func.isRequired, history: PropTypes.objectOf(PropTypes.any).isRequired }; static defaultProps = { user: null }; onFacebookLogin = async (err, data) => { if (err) return; const { login, history } = this.props; try { await login('facebook', data); this.successLogin(); } catch (error) { if (error.message === 'Incomplete oauth registration') { history.push({ pathname: '/register', state: { oauth: error.data } }); } else { throw error; } } }; onLocalLogin = async data => { const { login } = this.props; const result = await login('local', data); this.successLogin(); return result; }; successLogin = () => { const { notifSend } = this.props; notifSend({ message: "You're logged in now !", kind: 'success', dismissAfter: 2000 }); }; FacebookLoginButton = ({ facebookLogin }) => ( <button type="button" className="btn btn-primary" onClick={facebookLogin}> Login with <i className="fa fa-facebook-f" /> </button> ); render() { const { user, logout } = this.props; return ( <div className="container"> <Helmet title="Login" /> <h1>Login</h1> {!user && ( <div> <LoginForm onSubmit={this.onLocalLogin} /> <p>This will "log you in" as this user, storing the username in the session of the API server.</p> <FacebookLogin appId="635147529978862" /* autoLoad={true} */ fields="name,email,picture" onLogin={this.onFacebookLogin} component={this.FacebookLoginButton} /> </div> )} {user && ( <div> <p> You are currently logged in as {user.email}. </p> <div> <button type="button" className="btn btn-danger" onClick={logout}> <i className="fa fa-sign-out" /> Log Out </button> </div> </div> )} </div> ); } } export default Login;
docs/app/Examples/elements/Label/Types/index.js
koenvg/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const LabelTypes = () => ( <ExampleSection title='Types'> <ComponentExample title='Label' description='A label' examplePath='elements/Label/Types/LabelExampleBasic' /> <ComponentExample examplePath='elements/Label/Types/LabelExampleImage' /> <ComponentExample examplePath='elements/Label/Types/LabelExampleImageColored' /> <ComponentExample examplePath='elements/Label/Types/LabelExampleIcon' /> <ComponentExample title='Pointing' description='A label can point to content next to it' examplePath='elements/Label/Types/LabelExamplePointing' /> <ComponentExample examplePath='elements/Label/Types/LabelExamplePointingColored' /> <ComponentExample title='Corner' description='A label can position itself in the corner of an element' examplePath='elements/Label/Types/LabelExampleCorner' /> <ComponentExample title='Tag' description='A label can appear as a tag' examplePath='elements/Label/Types/LabelExampleTag' /> <ComponentExample title='Ribbon' description='A label can appear as a ribbon attaching itself to an element' examplePath='elements/Label/Types/LabelExampleRibbon' /> <ComponentExample examplePath='elements/Label/Types/LabelExampleRibbonImage' /> <ComponentExample title='Attached' description='A label can attach to a content segment' examplePath='elements/Label/Types/LabelExampleAttached' /> <ComponentExample title='Horizontal' description='A horizontal label is formatted to label content along-side it horizontally' examplePath='elements/Label/Types/LabelExampleHorizontal' /> <ComponentExample title='Floating' description='A label can float above another element' examplePath='elements/Label/Types/LabelExampleFloating' /> </ExampleSection> ) export default LabelTypes
client/modules/core/components/followlist.js
Entropy03/jianwei
import React from 'react'; import Paper from 'material-ui/Paper'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors'; import IconButton from 'material-ui/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; const style = { height: '100%', width: '18%', margin: 20, display: 'inline-block', }; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={grey400} /> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Reply</MenuItem> <MenuItem>Forward</MenuItem> <MenuItem>Delete</MenuItem> </IconMenu> ); const ListExampleMessages = () => ( <Paper style={style} zDepth={2}> <List> <Subheader>关注的事情</Subheader> <ListItem leftAvatar={<Avatar src="images/ok-128.jpg" />} primaryText="Brunch this weekend?" secondaryText={ <p> <span style={{color: darkBlack}}>Brendan Lim</span> -- I&apos;ll be in your neighborhood doing errands this weekend. Do you want to grab brunch? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kolage-128.jpg" />} primaryText={ <p>Summer BBQ&nbsp;&nbsp;<span style={{color: lightBlack}}>4</span></p> } secondaryText={ <p> <span style={{color: darkBlack}}>to me, Scott, Jennifer</span> -- Wish I could come, but I&apos;m out of town this weekend. </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/uxceo-128.jpg" />} primaryText="Oui oui" secondaryText={ <p> <span style={{color: darkBlack}}>Grace Ng</span> -- Do you have Paris recommendations? Have you ever been? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kerem-128.jpg" />} primaryText="Birdthday gift" secondaryText={ <p> <span style={{color: darkBlack}}>Kerem Suer</span> -- Do you have any ideas what we can get Heidi for her birthday? How about a pony? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />} primaryText="Recipe to try" secondaryText={ <p> <span style={{color: darkBlack}}>Raquel Parrado</span> -- We should eat this: grated squash. Corn and tomatillo tacos. </p> } secondaryTextLines={2} /> </List> </Paper> ); export default ListExampleMessages;
src/svg-icons/hardware/security.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSecurity = (props) => ( <SvgIcon {...props}> <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/> </SvgIcon> ); HardwareSecurity = pure(HardwareSecurity); HardwareSecurity.displayName = 'HardwareSecurity'; HardwareSecurity.muiName = 'SvgIcon'; export default HardwareSecurity;
src/svg-icons/file/attachment.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileAttachment = (props) => ( <SvgIcon {...props}> <path d="M2 12.5C2 9.46 4.46 7 7.5 7H18c2.21 0 4 1.79 4 4s-1.79 4-4 4H9.5C8.12 15 7 13.88 7 12.5S8.12 10 9.5 10H17v2H9.41c-.55 0-.55 1 0 1H18c1.1 0 2-.9 2-2s-.9-2-2-2H7.5C5.57 9 4 10.57 4 12.5S5.57 16 7.5 16H17v2H7.5C4.46 18 2 15.54 2 12.5z"/> </SvgIcon> ); FileAttachment = pure(FileAttachment); FileAttachment.displayName = 'FileAttachment'; FileAttachment.muiName = 'SvgIcon'; export default FileAttachment;
examples/1-multi/src/signup/index.js
chikara-chan/react-power
import React from 'react' import { render } from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './components/App' function renderHTML() { render( <AppContainer> <App /> </AppContainer>, document.getElementById('root') ) } renderHTML() if (module.hot) { module.hot.accept('./components/App', () => { renderHTML() }) }
app/js/components/Items/ItemListContainer.js
JeffRisberg/RE03
import React, { Component } from 'react'; import { connect } from 'react-redux'; import log from 'logger'; import { queryItems, toggleItem } from '../../actions/items'; import { AddItemComponent, ItemListComponent } from '../Items'; import './Items.scss'; class ItemListContainer extends Component { componentDidMount() { log.info('Fetching Items'); this.props.queryItems(); } render() { if (this.props.items != undefined) { return ( <div className="itemPage"> <AddItemComponent /> <ItemListComponent records={this.props.items} status={this.props.status} toggleItem={this.props.toggleItem}/> </div> ); } else { return null; } } } const mapStateToProps = (state) => ({ items: state.app.items.data, status: { isFetching: state.app.items.isFetching, ...state.app.appErrors, }, }); export default connect( mapStateToProps, { queryItems, toggleItem } )(ItemListContainer);
client/components/users/email-enrollment-form.js
wuyang910217/meteor-react-redux-base
import React from 'react'; export default class extends React.Component { constructor(props) { super(props); this.state = {uiState: 'INIT'}; this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); this.setState({uiState: 'SENDING'}); this.props.enrollWithEmail(this._input.value, (err) => { if (err) { console.log(err); this.setState({uiState: 'FAIL'}); } else { this.setState({uiState: 'SUCCESS'}); } }); } render() { if (this.state.uiState === 'SENDING') return <div>正在发送邮件...</div>; if (this.state.uiState === 'SUCCESS') return <div>邮件已发送,请查看您的邮箱</div>; return ( <div className="row"> <div className="col-sm-12"> {this.state.uiState === 'FAIL' && <p>邮件发送失败,请重试</p>} <p>请填写登录用的邮箱地址,我们将发送一个链接到你邮箱,通过该链接设置登录密码</p> <form onSubmit={this.onSubmit}> <div className="input-group"> <input className="form-control" type="text" ref={(c) => this._input = c}/> <span className="input-group-btn"> <button className="btn btn-default" type="submit">提交</button> </span> </div> </form> </div> </div> ); } }
test/specs/addons/Select/Select-test.js
vageeshb/Semantic-UI-React
import React from 'react' import Select from 'src/addons/Select/Select' import Dropdown from 'src/modules/Dropdown/Dropdown' import * as common from 'test/specs/commonTests' const requiredProps = { options: [], } describe('Select', () => { common.isConformant(Select, requiredProps) common.hasSubComponents(Select, [Dropdown.Divider, Dropdown.Header, Dropdown.Item, Dropdown.Menu]) it('renders a selection Dropdown', () => { shallow(<Select {...requiredProps} />) .first() .should.contain(<Dropdown {...requiredProps} selection />) }) })
app/templates/env/_web.js
Skookum/generator-genreact
require('isomorphic-fetch'); require('es6-promise').polyfill(); import React from 'react'; import { render } from 'react-dom'; import { Router } from 'react-router'; import { createHistory } from 'history'; import routes from '../routes'; const history = createHistory(); render( <Router children={routes} history={history} />, document.getElementById('app') );
frontend/component/Signup.js
wangmuming/node-forum
import React from 'react'; import jQuery from 'jquery'; import {signup} from '../lib/client'; import {redirectURL} from '../lib/utils'; export default class Signup extends React.Component{ constructor(pros){ super(pros); this.state = {}; } // 输入‘用户名’‘密码’检测 handleChange(name, e){ // console.log(name, e.target.value); this.state[name] = e.target.value; } // 点击‘登录’ handleLogin(e){ const $btn = jQuery(e.target); $btn.button('loading'); signup(this.state.name, this.state.email, this.state.password, this.state.nickname) .then(ret => { $btn.button('reset'); alert('注册成功!'); redirectURL('/login'); }) .catch(err => { $btn.button('reset'); alert(err); }); } render(){ return( <div style={{width: 400, margin: 'auto'}}> <div className="panel panel-primary"> <div className="panel-heading">注册</div> <div className="panel-body"> <form> <div className="form-group"> <label htmlFor="ipt-name">用户名</label> <input type="text" className="form-control" id="ipt-name" onChange={this.handleChange.bind(this, 'name')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="ipt-email">邮箱</label> <input type="text" className="form-control" id="ipt-email" onChange={this.handleChange.bind(this, 'email')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="ipt-nickname">昵称</label> <input type="text" className="form-control" id="ipt-nickname" onChange={this.handleChange.bind(this, 'nickname')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="password">密码</label> <input type="password" className="form-control" id="password" onChange={this.handleChange.bind(this, 'password')} placeholder="" /> </div> <button type="button" className="btn btn-primary" onClick={this.handleLogin.bind(this)}>注册</button> </form> </div> </div> </div> ); } }
src/components/CampViewItem/AboutCell/index.js
JamesJin038801/CampID
import React, { Component } from 'react'; import I18n from 'react-native-i18n'; import { connect } from 'react-redux'; import { View, Text, TouchableOpacity, Image, ScrollView, Alert } from 'react-native'; import { Styles, Metrics, Images, Colors, Fonts } from '@theme/'; import styles from './styles'; import CommonWidgets from '@components/CommonWidgets'; import Utils from '@src/utils'; import { Avatar } from 'react-native-elements'; class AboutCell extends Component { render() { return ( <View style={[styles.container, Styles.rowContainer]}> <View style={Styles.center}> {CommonWidgets.renderSizedAvatar(this.props.imgPath, null, Metrics.aboutAvatarSize)} </View> <View style={{ width: 20 }} /> <View style={{ flex: 1, justifyContent: 'center' }}> <Text style={{ ...Fonts.style.h4, color: Colors.brandPrimary }}>{this.props.name}</Text> <Text style={{ ...Fonts.style.h4, color: Colors.textPrimary }}>{this.props.job}</Text> <Text style={{ ...Fonts.style.h4, color: Colors.textPrimary }}>{this.props.school}</Text> </View> </View> ); } } AboutCell.propTypes = { imgPath: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, job: React.PropTypes.string.isRequired, school: React.PropTypes.string.isRequired, }; AboutCell.defaultProps = { imgPath: 'https://facebook.github.io/react/img/logo_og.png', name: 'All American', job: "Head-Coach: Women's Basketball", school: 'Washington University', }; function mapStateToProps(state) { const globals = state.get('globals'); return { globals }; } export default connect(mapStateToProps, null)(AboutCell);
ui/js/pages/page/PagesItemEdit.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FormField from '../../components/FormField'; // import ImageField from '../../components/ImageField'; import SelectSearch from '../../components/SelectSearch'; import TextHelp from '../../components/TextHelp'; import FormState from '../../utils/FormState'; export default class PageItemEdit extends Component { constructor(props) { super(props); const { onChange, item } = props; this.state = { formState: new FormState(item, onChange) }; } componentWillReceiveProps(nextProps) { const { onChange, item } = nextProps; this.setState({ formState: new FormState(item, onChange) }); } render() { // const { index } = this.props; const { formState } = this.state; const pageSummary = formState.object; return ( <div> <FormField label="Page"> <SelectSearch category="pages" value={pageSummary.id ? pageSummary.id.name : ''} onChange={suggestion => formState.change('id')({ _id: suggestion._id, name: suggestion.name })} /> </FormField> <FormField name="summary" label="Summary" help={<TextHelp />}> <textarea name="summary" value={pageSummary.summary || ''} rows={4} onChange={formState.change('summary')} /> </FormField> {/* } <ImageField key="image" label="Image" name={`image-${index}`} formState={formState} property="image" /> { */} </div> ); } } PageItemEdit.propTypes = { // index: PropTypes.number.isRequired, item: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, };
client2/src/components/Video/components/video_detail.js
frolicking-ampersand/Board
import React, { Component } from 'react'; import Youtube from 'react-youtube'; export default class VideoDetail extends Component { constructor(props){ super(props) this.state={ player: null } this.setPlayer = this.setPlayer.bind(this); this.sendPlayData = this.sendPlayData.bind(this); this.playVideo = this.playVideo.bind(this); this.sendPauseData = this.sendPauseData.bind(this); this.pauseVideo = this.pauseVideo.bind(this); } componentDidMount() { this.socket = io(); this.socket.on('playVideo', function (data) { this.setState({term: data.term}); }.bind(this)); this.socket.on('recievePlay', this.playVideo); this.socket.on('recievePause', this.pauseVideo); } setPlayer(event) { this.setState({ player: event.target, }); } sendPlayData() { this.socket.emit('sendPlay'); } playVideo(){ this.state.player.playVideo(); } sendPauseData() { this.socket.emit('sendPause'); } pauseVideo () { this.state.player.pauseVideo(); } render() { if(!this.props.video){ return ( <img className="loading-styles" src="./media/spinner.gif" /> ) } return ( <div className="video-detail col-md-12 animated slideInUp"> <div className="embed-responsive embed-responsive-16by9"> <Youtube videoId={this.props.video.id.videoId} onReady={this.setPlayer} onPlay={this.sendPlayData} onPause={this.sendPauseData} /> </div> </div> ); } };
packages/react-scripts/fixtures/kitchensink/src/features/env/PublicUrl.js
josephfinlayson/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react' export default () => ( <span id="feature-public-url">{process.env.PUBLIC_URL}.</span> )
egghead.io/create-react-app/src/Updates.js
andrisazens/learning_react
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class App extends Component { constructor() { super(); this.state = { increasing: false }; } update(e) { ReactDOM.render(<App val={this.props.val + 1} />, document.getElementById("root")) } componentWillReceiveProps(nextProps) { this.setState({ increasing: nextProps.val > this.props.val }) } shouldComponentUpdate(nextProps, nextState) { return nextProps.val % 3 === 0; } render() { console.log(this.state.increasing); return ( <button onClick={this.update.bind(this) }> {this.props.val} </button> ) } componentDidUpdate(prevProps, prevState){ console.log(`prevProps: ${prevProps.val}`) } } App.defaultProps = { val: 0 } export default App;
client/src/pages/year-end-gift.js
BhaveshSGupta/FreeCodeCamp
import React from 'react'; import Helmet from 'react-helmet'; import { Grid } from '@freecodecamp/react-bootstrap'; import { Spacer, FullWidthRow } from '../components/helpers'; import YearEndDonationForm from '../components/YearEndGift/YearEndDonationForm'; function YearEndGiftPage() { return ( <> <Helmet title='Support our nonprofit | freeCodeCamp.org' /> <Grid> <main> <Spacer /> <FullWidthRow> <YearEndDonationForm defaultTheme='light' /> </FullWidthRow> <Spacer /> <Spacer /> </main> </Grid> </> ); } YearEndGiftPage.displayName = 'YearEndGiftPage'; export default YearEndGiftPage;
ui/src/app.js
untoldwind/eightyish
import React from 'react' import { Route, DefaultRoute, RouteHandler, run } from 'react-router' import MenuBar from './components/MenuBar' import MachineView from './components/MachineView' import InstructionSetView from './components/InstructionSetView' export default class App extends React.Component { render() { return ( <div> <MenuBar/> <div className="container"> <RouteHandler /> </div> </div> ) } } const routes = ( <Route handler={App}> <DefaultRoute handler={MachineView} name="simulator"/> <Route handler={InstructionSetView} name="instructionSet"/> </Route> ) run(routes, (Handler) => React.render(<Handler/>, document.getElementById('app')))
app/components/Spacer.js
ixje/neon-wallet-react-native
import React from 'react' import { View } from 'react-native' class Spacer extends React.Component { render() { return ( <View style={{ height: 2, backgroundColor: '#EFEFEF', marginHorizontal: 30, marginVertical: 20 }} /> ) } } export default Spacer
src/svg-icons/av/airplay.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAirplay = (props) => ( <SvgIcon {...props}> <path d="M6 22h12l-6-6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); AvAirplay = pure(AvAirplay); AvAirplay.displayName = 'AvAirplay'; AvAirplay.muiName = 'SvgIcon'; export default AvAirplay;
src/app/Sidebar/Navigation.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getAuthenticatedUser, getIsTrendingTopicsLoading, getTrendingTopics } from '../../reducers'; import Topics from '../../components/Sidebar/Topics'; import Sidenav from '../../components/Navigation/Sidenav'; const Navigation = ({ authenticatedUser, trendingTopicsLoading, trendingTopics }) => ( <div> <Sidenav username={authenticatedUser.name} /> <Topics loading={trendingTopicsLoading} topics={trendingTopics} /> </div> ); Navigation.propTypes = { authenticatedUser: PropTypes.shape().isRequired, trendingTopicsLoading: PropTypes.bool.isRequired, trendingTopics: PropTypes.arrayOf(PropTypes.string).isRequired, }; export default connect( state => ({ authenticatedUser: getAuthenticatedUser(state), trendingTopicsLoading: getIsTrendingTopicsLoading(state), trendingTopics: getTrendingTopics(state), }), )(Navigation);
react/gameday2/components/embeds/EmbedLivestream.js
jaredhasenklein/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedLivestream = (props) => { const channel = props.webcast.channel const file = props.webcast.file const iframeSrc = `https://new.livestream.com/accounts/${channel}/events/${file}/player?width=640&height=360&autoPlay=true&mute=false` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" allowFullScreen /> ) } EmbedLivestream.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedLivestream
src/common/FaButton.js
FredBoat/fredboat.com
import React, { Component } from 'react'; import {Link} from 'react-router-dom'; import FontAwesome from 'react-fontawesome'; import "./css/FaButton.css"; class FaButton extends Component { //noinspection JSMethodCanBeStatic render() { const linkInner = ( <div className="fabutton-shade"> <div className="fabutton-inner"> <FontAwesome name={this.props.icon}/> <div className="fabutton-text"> {this.props.text} </div> </div> </div> ); // Check if <a> tag is required or router Link tag. Link tags do not support other origins if (/[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/.test(this.props.to)) { return ( <div className="FaButton"> <a href={this.props.to} style={{backgroundColor: this.props.color}}> {linkInner} </a> </div> ) } else { return ( <div className="FaButton"> <Link to={this.props.to} style={{backgroundColor: this.props.color}}> {linkInner} </Link> </div> ) } } } export default FaButton;
src/svg-icons/alert/error.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertError = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/> </SvgIcon> ); AlertError = pure(AlertError); AlertError.displayName = 'AlertError'; AlertError.muiName = 'SvgIcon'; export default AlertError;
client/modules/users/components/.stories/dashboard.js
StorytellerCZ/Socialize-starter
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { setComposerStub } from 'react-komposer'; import Dashboard from '../dashboard.jsx'; storiesOf('users.Dashboard', module) .add('default view', () => { return ( <Dashboard /> ); })
packages/ndla-icons/src/common/Time.js
netliferesearch/frontend-packages
/** * Copyright (c) 2017-present, NDLA. * * This source code is licensed under the GPLv3 license found in the * LICENSE file in the root directory of this source tree. * */ // N.B! AUTOGENERATED FILE. DO NOT EDIT import React from 'react'; import Icon from '../Icon'; const Time = props => ( <Icon viewBox="0 0 48 48" data-license="Apache License 2.0" data-source="Material Design" {...props}> <g> <path d="M23.99 4C12.94 4 4 12.95 4 24s8.94 20 19.99 20C35.04 44 44 35.05 44 24S35.04 4 23.99 4zM24 40c-8.84 0-16-7.16-16-16S15.16 8 24 8s16 7.16 16 16-7.16 16-16 16zm1-26h-3v12l10.49 6.3L34 29.84l-9-5.34z" /> </g> </Icon> ); export default Time;
src/svg-icons/image/colorize.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageColorize = (props) => ( <SvgIcon {...props}> <path d="M20.71 5.63l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z"/> </SvgIcon> ); ImageColorize = pure(ImageColorize); ImageColorize.displayName = 'ImageColorize'; ImageColorize.muiName = 'SvgIcon'; export default ImageColorize;
index.android.js
GTXPRO/Reactnative
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; //import App from './Components/App'; import Nav from './Components/Nav'; export default class Realtime extends Component { render() { return ( <Nav /> ); } } AppRegistry.registerComponent('Realtime', () => Realtime);
test/generate/build-component-test-test.js
jeffbuttars/rj
import test from 'ava' import buildComponentTest from '../../src/generate/build-component-test' const expected = `import test from 'ava' import React from 'react' import sinon from 'sinon' import { render } from 'react-dom' import { renderToStaticMarkup } from 'react-dom/server' import { Simulate } from 'react-addons-test-utils' import Awesome from './Awesome' test('does something awesome', t => { const output = renderStatic() t.true(output.includes('children')) }) function renderStatic (props) { return renderToStaticMarkup(<Awesome {...props} />) } function renderToDiv (props) { const div = document.createElement('div') render ( <Awesome {...props}> {props.children || 'ohai!'} </Awesome>, div ) return div } ` test('creates component test', t => { t.plan(1) const output = buildComponentTest('awesome', { props: ['foo:number:required', 'bar'] }) t.same(output, expected) })
examples/flux-utils-todomvc/js/app.js
RomanTsopin/flux
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import React from 'react'; import TodoApp from './components/TodoApp.react'; React.render(<TodoApp />, document.getElementById('todoapp'));
src/layouts/Contact.js
akhatri/portfolio-website
import React, { Component } from 'react'; import ContactImage from '../images/get-in-touch.jpg'; // Libraries import Fade from 'react-reveal/Fade'; class Contact extends Component { constructor() { super(); } render() { return ( <Fade> <section id="contact" className="bg-grey"> <div className="container py-5"> <h1>Get in touch <span className="emoji" aria-label="Emoji heart letter" role="img">💌</span></h1> <div className="grid-wrapper col-2 align-center grid-gap-4"> <img className="img-fluid rounded" src={ContactImage} alt="Get in touch" /> <div> <p>If you would like to get in touch regarding any freelance consulting projects and start-up advice on technology roadmaps, please get in touch through my business website <a href="https://nimblestudios.dev/">Nimble Studios</a> <span aria-label="Emoji smiley" role="img">😄</span></p> </div> </div> </div> </section> </Fade> ); } } export default Contact;
src/svg-icons/image/dehaze.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageDehaze = (props) => ( <SvgIcon {...props}> <path d="M2 15.5v2h20v-2H2zm0-5v2h20v-2H2zm0-5v2h20v-2H2z"/> </SvgIcon> ); ImageDehaze = pure(ImageDehaze); ImageDehaze.displayName = 'ImageDehaze'; ImageDehaze.muiName = 'SvgIcon'; export default ImageDehaze;
stories/Combobox/AsyncDemo.js
propertybase/react-lds
import React, { Component } from 'react'; import { debounce, without } from 'lodash-es'; import { BASE_ITEMS } from './constants'; import { EntityCombobox } from '../../src'; const mockSearchResults = BASE_ITEMS.map((item, i) => ({ ...item, isDisabled: i === 2, icon: { sprite: 'standard', icon: 'groups' }, meta: <span>Objects • Standard</span> })); export class AsyncComboboxDemo extends Component { constructor(props) { super(props); this.state = { isLoading: false, isOpen: false, items: mockSearchResults, search: '', selection: [], }; this.performSearch = debounce(this.performSearch, 300); } performSearch = () => { this.setState({ isLoading: true }); console.log('Loading new items...'); // eslint-disable-line setTimeout(() => { this.setState({ isLoading: false }); }, 1000); } onSearch = (val) => { this.setState({ search: val }); if (val !== '') this.performSearch(val); } onSelect = (id, { isAdd, isReplace, isRemove }) => { if (isReplace) { this.setState({ selection: [].concat(id), }); } else if (isRemove) { this.setState(({ selection: prevSelection }) => ({ selection: without(prevSelection, id), })); } else if (!isAdd) { this.setState(({ selection: prevSelection }) => ({ selection: [...prevSelection, id], })); } } onToggle = (nextOpen) => { this.setState({ isOpen: nextOpen }); } render() { const { isLoading, isOpen, items, search, selection } = this.state; const selectedItems = selection.map(id => items.find(item => item.id === id)); return ( <EntityCombobox {...this.props} isLoading={isLoading} isOpen={isOpen} items={isLoading ? [] : items} onSearch={this.onSearch} onSelect={this.onSelect} onToggle={this.onToggle} search={search} selectedItems={selectedItems} /> ); } }
src/components/ButtonWarning.js
mikebarkmin/gestyled
import React from 'react'; import { withTheme } from 'styled-components'; import Button from './Button'; /** * See Button for possible props. */ const ButtonWarning = props => { const { theme } = props; const bg = theme.colors.warning; const color = theme.colors.warningText; return <Button bg={bg} color={color} {...props} />; }; export default withTheme(ButtonWarning);
assets/registration/components/DynamicFieldsSkills.js
janta-devs/nyumbani
import React, { Component } from 'react'; import AddButton from './AddButton'; import Fieldskill from './Fieldskill'; var y = [[1],]; class DynamicFieldsSkills extends Component{ constructor( context, props ){ super( context, props ); this.state = { count: 1, fields: [] } } _getAction( event ){ event.preventDefault(); this.setState({ count: this.state.count += 1}); y.push( this.state.count ); this.setState({fields: y }); } render(){ var populate = y.map( y => <Fieldskill key = {y} unique = {y} getValue = {this.props.getValue}/> ); return ( <div> {populate} <br /> <AddButton getAction = {this._getAction.bind(this)} /> </div> );a } }; export default DynamicFieldsSkills;
src/svg-icons/av/explicit.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvExplicit = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"/> </SvgIcon> ); AvExplicit = pure(AvExplicit); AvExplicit.displayName = 'AvExplicit'; AvExplicit.muiName = 'SvgIcon'; export default AvExplicit;
example_component.js
roscoe054/react-markdown-gen
import React, { Component } from 'react'; /** * General component description. */ export default class MyComponent extends Component { render() { // ... } } MyComponent.defaultProps = { showPagination: true, paginationColor: '#09c', paginationSpace: 20 } MyComponent.propTypes = { /** Description of prop "children". */ children: React.PropTypes.node.isRequired, showPagination: React.PropTypes.bool, paginationColor: React.PropTypes.string, paginationSpace: React.PropTypes.number, }
src/js/views/lists.js
electronspin/touchstonejs-starter
import Container from 'react-container'; import React from 'react'; import { Link, UI } from 'touchstonejs'; module.exports = React.createClass({ statics: { navigationBar: 'main', getNavigation () { return { title: 'Lists' } } }, render: function () { return ( <Container scrollable> <UI.Group> <UI.GroupHeader>Lists</UI.GroupHeader> <UI.GroupBody> <Link to="tabs:list-simple" transition="show-from-right"> <UI.Item showDisclosureArrow> <UI.ItemInner> Simple List </UI.ItemInner> </UI.Item> </Link> <Link to="tabs:list-complex" transition="show-from-right"> <UI.Item showDisclosureArrow> <UI.ItemInner> Complex List </UI.ItemInner> </UI.Item> </Link> </UI.GroupBody> </UI.Group> <UI.Group> <UI.GroupHeader>GroupHeader</UI.GroupHeader> <UI.GroupBody> <UI.GroupInner> <p>Use groups to contain content or lists. Where appropriate a Group should be accompanied by a GroupHeading and optionally a GroupFooter.</p> GroupBody will apply the background for content inside groups. </UI.GroupInner> </UI.GroupBody> <UI.GroupFooter>GroupFooter: useful for a detailed explaination to express the intentions of the Group. Try to be concise - remember that users are likely to read the text in your UI many times.</UI.GroupFooter> </UI.Group> </Container> ); } });
example/src/components/SliderEntry.js
houseofstylist/react-native-snap-carousel
import React, { Component } from 'react'; import { View, Text, Image, TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types'; import { ParallaxImage } from 'react-native-snap-carousel'; import styles from 'example/src/styles/SliderEntry.style'; export default class SliderEntry extends Component { static propTypes = { data: PropTypes.object.isRequired, even: PropTypes.bool, parallax: PropTypes.bool, parallaxProps: PropTypes.object }; get image () { const { data: { illustration }, parallax, parallaxProps, even } = this.props; return parallax ? ( <ParallaxImage source={{ uri: illustration }} containerStyle={[styles.imageContainer, even ? styles.imageContainerEven : {}]} style={styles.image} parallaxFactor={0.35} showSpinner={true} spinnerColor={even ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.25)'} {...parallaxProps} /> ) : ( <Image source={{ uri: illustration }} style={styles.image} /> ); } render () { const { data: { title, subtitle }, even } = this.props; const uppercaseTitle = title ? ( <Text style={[styles.title, even ? styles.titleEven : {}]} numberOfLines={2} > { title.toUpperCase() } </Text> ) : false; return ( <TouchableOpacity activeOpacity={1} style={styles.slideInnerContainer} onPress={() => { alert(`You've clicked '${title}'`); }} > <View style={styles.shadow} /> <View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}> { this.image } <View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} /> </View> <View style={[styles.textContainer, even ? styles.textContainerEven : {}]}> { uppercaseTitle } <Text style={[styles.subtitle, even ? styles.subtitleEven : {}]} numberOfLines={2} > { subtitle } </Text> </View> </TouchableOpacity> ); } }
src/examples/ExampleComponent.js
alickzhang/react-responsive-music-player
import React from 'react'; import BasicPlayer from './BasicPlayer'; import VerticalPlayer from './VerticalPlayer'; export default () => ( <div> <BasicPlayer /> <VerticalPlayer /> </div> );
src/svg-icons/editor/format-align-right.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatAlignRight = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"/> </SvgIcon> ); EditorFormatAlignRight = pure(EditorFormatAlignRight); EditorFormatAlignRight.displayName = 'EditorFormatAlignRight'; EditorFormatAlignRight.muiName = 'SvgIcon'; export default EditorFormatAlignRight;
lib-es/components/media/media.js
bokuweb/re-bulma
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../../build/styles'; import { getCallbacks } from './../../helper/helper'; export default class Media extends Component { createClassName() { return [styles.media, this.props.className].join(' ').trim(); } render() { return React.createElement( 'article', _extends({}, getCallbacks(this.props), { style: this.props.style, className: this.createClassName() }), this.props.children ); } } Media.propTypes = { style: PropTypes.object, children: PropTypes.any, className: PropTypes.string }; Media.defaultProps = { style: {}, className: '' };
docs/src/app/components/pages/components/Card/Page.js
pradel/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import cardReadmeText from './README'; import cardExampleWithAvatarCode from '!raw!./ExampleWithAvatar'; import CardExampleWithAvatar from './ExampleWithAvatar'; import cardExampleWithoutAvatarCode from '!raw!./ExampleWithoutAvatar'; import CardExampleWithoutAvatar from './ExampleWithoutAvatar'; import cardExampleControlledCode from '!raw!./ExampleControlled'; import CardExampleControlled from './ExampleControlled'; import cardCode from '!raw!material-ui/lib/Card/Card'; import cardActionsCode from '!raw!material-ui/lib/Card/CardActions'; import cardHeaderCode from '!raw!material-ui/lib/Card/CardHeader'; import cardMediaCode from '!raw!material-ui/lib/Card/CardMedia'; import cardTextCode from '!raw!material-ui/lib/Card/CardText'; import cardTitleCode from '!raw!material-ui/lib/Card/CardTitle'; const descriptions = { avatar: 'A `Card` containing each of the card components: `CardHeader` (with avatar), `CardMedia` (with overlay), ' + '`CardTitle`, `CardText` & `CardActions`.', simple: 'An expandable `Card` with `CardHeader`, `CardText` and `CardActions`. ' + 'Use the icon to expand the card.', controlled: 'A controlled expandable `Card`. Use the icon, the toggle or the ' + 'buttons to control the expanded state of the card.', }; const CardPage = () => ( <div> <Title render={(previousTitle) => `Card - ${previousTitle}`} /> <MarkdownElement text={cardReadmeText} /> <CodeExample title="Card components example" description={descriptions.avatar} code={cardExampleWithAvatarCode} > <CardExampleWithAvatar /> </CodeExample> <CodeExample title="Expandable example" description={descriptions.simple} code={cardExampleWithoutAvatarCode} > <CardExampleWithoutAvatar /> </CodeExample> <CodeExample title="Controlled example" description={descriptions.controlled} code={cardExampleControlledCode} > <CardExampleControlled /> </CodeExample> <PropTypeDescription code={cardCode} header="### Card properties" /> <PropTypeDescription code={cardActionsCode} header="### CardActions properties" /> <PropTypeDescription code={cardHeaderCode} header="### CardHeader properties" /> <PropTypeDescription code={cardMediaCode} header="### CardMedia properties" /> <PropTypeDescription code={cardTextCode} header="### CardText properties" /> <PropTypeDescription code={cardTitleCode} header="### CardTitle properties" /> </div> ); export default CardPage;
src/js/index.js
slavapavlutin/pavlutin-node
import 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import logger from 'redux-logger'; import { Provider } from 'react-redux'; import { AppContainer } from 'react-hot-loader'; import App from './components/App'; import rootReducer from './store/root/reducers'; const storeParams = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(); let middleware; if (process.env.NODE_ENV !== 'production') { middleware = applyMiddleware(thunk, logger); } else { middleware = applyMiddleware(thunk); } const store = createStore( rootReducer, storeParams, middleware, ); const appProvider = ( <AppContainer> <Provider store={store}> <App /> </Provider> </AppContainer> ); ReactDOM.render(appProvider, document.querySelector('.react-app')); if (module.hot) { module.hot.accept('./components/App', () => { ReactDOM.render( <AppContainer> <Provider store={store}> <App /> </Provider> </AppContainer>, document.querySelector('.app'), ); }); }
modules/Route.js
cojennin/react-router
import React from 'react' import warning from 'warning' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { component, components } from './PropTypes' const { string, bool, func } = React.PropTypes /** * A <Route> is used to declare which components are rendered to the page when * the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. */ const Route = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.handler) { warning( false, '<Route handler> is deprecated, use <Route component> instead' ) route.component = route.handler delete route.handler } return route } }, propTypes: { path: string, ignoreScrollBehavior: bool, handler: component, // deprecated component, components, getComponents: func }, render() { invariant( false, '<Route> elements are for router configuration only and should not be rendered' ) } }) export default Route
js/components/pages/Guide.js
juhojo/corejumper
import React from 'react'; import SubPage from '../reusable/SubPage.js'; import SubPageContent from '../reusable/SubPageContent.js'; import KeyboardKey from '../reusable/KeyboardKey'; export default class Guide extends SubPage{ render (){ return ( <SubPageContent {...this.props}> <h1>Guide</h1> <h2>Objective</h2> <ul> <li>avoid obstacles</li> <li>avoid center</li> <li>collect stars</li> <li>as fast as you can</li> </ul> <h2>Controls on a touch device:</h2> <p>Tap ☟ anywhere to jump</p> <p>Swipe ↔ anywhere to move</p> <h2>Controls on a keyboard:</h2> <p><KeyboardKey>↑</KeyboardKey>/<KeyboardKey>W</KeyboardKey>/<KeyboardKey>space</KeyboardKey> to jump</p> <p><KeyboardKey>←</KeyboardKey><KeyboardKey>→</KeyboardKey>/<KeyboardKey>A</KeyboardKey><KeyboardKey>D</KeyboardKey> to move</p> <p><KeyboardKey>Esc</KeyboardKey>/<KeyboardKey>pause break</KeyboardKey>/<KeyboardKey>Backspace</KeyboardKey> to pause</p> <h2>Navigation</h2> <p>In addition to clicking and tapping, you can navigate all menus using <KeyboardKey>↑</KeyboardKey><KeyboardKey>←</KeyboardKey><KeyboardKey>↓</KeyboardKey><KeyboardKey>→</KeyboardKey> and <KeyboardKey>W</KeyboardKey><KeyboardKey>A</KeyboardKey><KeyboardKey>S</KeyboardKey><KeyboardKey>D</KeyboardKey></p> </SubPageContent> ); } }
Youtuber-JS/src/components/video_list_item.js
victorditadi/IQApp
import React from 'react'; const VideoListItem = ({video, onVideoSelect}) => { const imageUrl = video.snippet.thumbnails.high.url; const titleVideo = video.snippet.title; const channelTitle = video.snippet.channelTitle; // const dataPublish = video.snippet.publishedAt; return( <div style={{cursor: 'pointer'}} className="col s12 m12 l11 offset-l1" onClick={() => onVideoSelect(video)}> <div className="card-panel grey lighten-5 z-depth-1" > <div className="row valign-wrapper"> <div className="col s6"> <img src={imageUrl} height={100} width={120} alt=""/> </div> <div className="col s10"> <h6><strong>{titleVideo}</strong></h6> <span className="black-text"> {channelTitle}<br/> </span> </div> </div> </div> </div> ); }; export default VideoListItem;
node_modules/@material-ui/core/es/Stepper/Stepper.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Paper from '../Paper'; import StepConnector from '../StepConnector'; export const styles = { /* Styles applied to the root element. */ root: { display: 'flex', padding: 24 }, /* Styles applied to the root element if `orientation="horizontal"`. */ horizontal: { flexDirection: 'row', alignItems: 'center' }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { flexDirection: 'column' }, /* Styles applied to the root element if `alternativeLabel={true}`. */ alternativeLabel: { alignItems: 'flex-start' } }; const defaultConnector = React.createElement(StepConnector, null); const Stepper = React.forwardRef(function Stepper(props, ref) { const { activeStep = 0, alternativeLabel = false, children, classes, className: classNameProp, connector: connectorProp = defaultConnector, nonLinear = false, orientation = 'horizontal' } = props, other = _objectWithoutPropertiesLoose(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]); const className = clsx(classes.root, classes[orientation], alternativeLabel && classes.alternativeLabel, classNameProp); const connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, { orientation }) : null; const childrenArray = React.Children.toArray(children); const steps = childrenArray.map((step, index) => { const controlProps = { alternativeLabel, connector: connectorProp, last: index + 1 === childrenArray.length, orientation }; const state = { index, active: false, completed: false, disabled: false }; if (activeStep === index) { state.active = true; } else if (!nonLinear && activeStep > index) { state.completed = true; } else if (!nonLinear && activeStep < index) { state.disabled = true; } return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({ key: index }, state)), React.cloneElement(step, _extends({}, controlProps, state, step.props))]; }); return React.createElement(Paper, _extends({ square: true, elevation: 0, className: className, ref: ref }, other), steps); }); process.env.NODE_ENV !== "production" ? Stepper.propTypes = { /** * Set the active step (zero based index). */ activeStep: PropTypes.number, /** * If set to 'true' and orientation is horizontal, * then the step label will be positioned under the icon. */ alternativeLabel: PropTypes.bool, /** * Two or more `<Step />` components. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * A component to be placed between each step. */ connector: PropTypes.element, /** * If set the `Stepper` will not assist in controlling steps for linear flow. */ nonLinear: PropTypes.bool, /** * The stepper orientation (layout flow direction). */ orientation: PropTypes.oneOf(['horizontal', 'vertical']) } : void 0; export default withStyles(styles, { name: 'MuiStepper' })(Stepper);
app/components/Main.js
BenGoldstein88/hitch-frontend
import React from 'react'; export default class Main extends React.Component { render() { return ( <div>{this.props.children}</div> ); } }
src/components/Footer/Footer.js
cuitianze/demo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import s from './Footer.scss'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; @withStyles(s) class Footer extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/">Home</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/privacy">Privacy</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/not-found">Not Found</Link> </div> </div> ); } } export default Footer;
packages/material-ui-icons/src/Dehaze.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M2 15.5v2h20v-2H2zm0-5v2h20v-2H2zm0-5v2h20v-2H2z" /></g> , 'Dehaze');
src/components/common/svg-icons/maps/local-pizza.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPizza = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); MapsLocalPizza = pure(MapsLocalPizza); MapsLocalPizza.displayName = 'MapsLocalPizza'; MapsLocalPizza.muiName = 'SvgIcon'; export default MapsLocalPizza;
src/svg-icons/image/camera-alt.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraAlt = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/> </SvgIcon> ); ImageCameraAlt = pure(ImageCameraAlt); ImageCameraAlt.displayName = 'ImageCameraAlt'; ImageCameraAlt.muiName = 'SvgIcon'; export default ImageCameraAlt;
docs/src/app/pages/components/Buttons/ExampleButtonAnchor.js
GetAmbassador/react-ions
import React from 'react' import ButtonAnchor from 'react-ions/lib/components/Button/ButtonAnchor' const ExampleButtonAnchor = () => ( <div> <ButtonAnchor path='http://www.google.com' optClass='success'>External</ButtonAnchor> <ButtonAnchor path='http://www.google.com' target='_blank' collapse={true}>External (new window)</ButtonAnchor> <ButtonAnchor path='/components/progress-bar' internal={true} optClass='plain'>Internal</ButtonAnchor> <ButtonAnchor disabled path='/components/progress-bar' internal={true} optClass='secondary'>Disabled</ButtonAnchor> </div> ) export default ExampleButtonAnchor
test/helpers/shallowRenderHelper.js
RUTH2013/gallery-by-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
src/data-loader/view/DataContainer.js
sozemego/StatHelper
import React from 'react'; import {connect} from 'react-redux'; import operations from '../operations'; import FileUploadComponent from './FileUploadComponent'; import DataDisplayComponent from './DataDisplayComponent'; import selectors from '../selectors'; export class DataContainer extends React.Component { constructor(props) { super(props); } render() { const { onFileUpload, loading, itemNames } = this.props; return ( <div> <FileUploadComponent onFileUpload={onFileUpload} loading={loading}/> <DataDisplayComponent itemNames={itemNames}/> </div> ); } } const mapStateToProps = state => { const dataLoader = selectors.dataLoaderRootSelector(state); return { itemNames: selectors.getItemNames(dataLoader), loading: selectors.isLoading(dataLoader), error: selectors.getError(dataLoader) }; }; const dispatchToProps = dispatch => { return { onFileUpload: file => { dispatch(operations.loadFile(file)); } }; }; export default connect(mapStateToProps, dispatchToProps)(DataContainer);
anubis/frontend/src/components/footer.js
cmspsgp31/anubis
// Copyright © 2016, Ugo Pozo // 2016, Câmara Municipal de São Paulo // footer.js - footer component of the search interface. // This file is part of Anubis. // Anubis is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Anubis is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import {connect} from 'react-redux'; import {Toolbar, ToolbarGroup, ToolbarTitle} from 'material-ui'; import {PropTypes as RPropTypes} from 'react'; const getStateProps = state => ({ footer: state.getIn(['applicationData', 'footer']), }); @connect(getStateProps) export default class Header extends React.Component { static propTypes = { footer: RPropTypes.string, } static contextTypes = { muiTheme: React.PropTypes.object, } render() { const color = this.context.muiTheme.flatButton.textColor; return ( <Toolbar style={{ boxShadow: "0 -10px 15px 0 rgba(0,0,0,0.4)", position: "fixed", bottom: 0, width: "100%", fontFamily: "'Roboto', sans-serif", zIndex: 1500, }} > <ToolbarGroup> <ToolbarTitle style={{color}} text={this.props.footer} /> </ToolbarGroup> </Toolbar> ); } }
demo/examples/themes/morty-theme.js
rcaferati/react-awesome-button
import React from 'react'; import { ThemeTest } from '../../components'; import Modules from '../../helpers/modules'; import { features, properties, examples } from '../common'; const THEME = 'theme-c137'; const items = examples(THEME); const component = ( <ThemeTest theme={THEME} /> ); const module = Modules.Modules[THEME]; const example = { title: 'Get your shit together.', description: 'AwesomeButton Generic Example', items, component, componentClass: Modules.Modules['theme-c137']['aws-btn'], }; export default { features, example, module, properties, };
src/pages/home.js
ChrisMichaelPerezSantiago/CodetrotterFinalProject
// npm packages import _ from 'lodash'; import React from 'react'; import {Observable} from 'rxjs'; // my packages import db from '../db'; import {Crunchyroll} from '../api'; // my components import Navbar from '../components/navbar'; import Series from '../components/series'; export default class Home extends React.Component { constructor() { super(); this.state = { series: [], }; // trigger list update Crunchyroll.getAllSeries(); } componentDidMount() { this.sub = Observable.fromEvent( db.series.changes({ since: 0, live: true, include_docs: true, }), 'change' ) .filter(change => !change.deleted) .map(change => change.doc) .scan((acc, doc) => acc.concat([doc]), []) .debounceTime(1000) .subscribe(series => this.setState({series})); } componentWillUnmount() { this.sub.unsubscribe(); } render() { const {series} = this.state; return ( <div> <Navbar /> {_.chunk(series, 4).map((chunk, i) => ( <div key={`chunk_${i}`} className="tile is-ancestor"> {chunk.map(s => <Series key={s._id} series={s} />)} </div> ))} <footer className="footer"> <div className="container"> <div className="content has-text-centered"> <p> <strong>Japanistic Anime</strong> by <a>Chris M. Perez</a>. The source code is licensed <a> MIT.</a> </p> <p> <a className="icon"> <i className="fa fa-github"></i> </a> </p> </div> </div> </footer> </div> ); } }
src/App.js
chesterhow/js-stack
// @flow import React from 'react'; import { HashRouter as Router, Route } from 'react-router-dom'; import Dev from './containers/Dev'; import Test from './containers/Test'; import './stylesheets/styles.scss'; const App = () => ( <Router basename="/"> <div> <Route exact path="/" render={(props) => <Dev {...props} />} /> <Route path="/testing" render={(props) => <Test {...props} />} /> </div> </Router> ); export default App;
src/app/components/panels/Error.js
jimmed/spankhbot
import React from 'react'; import cx from 'suitcx'; export default function Error({ message, severity }) { return ( <div className={cx('Panel')}> <div className="top-bar"> <div className="top-bar-left"> <div className="menu-text">Error</div> </div> </div> <div className={`callout ${severity}`}> <h5>Unknown panel</h5> <p> {message} </p> </div> </div> ); }
demos/forms-demo/src/components/PrettyPrint/index.js
idream3/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state, props} from 'cerebral/tags' import {isValidForm, getInvalidFormFields, formToJSON} from 'cerebral-forms' import {css} from 'aphrodite' import syntaxHighlight from '../../helpers/syntaxHighlight' import styles from './styles' export default connect({ form: state`${props`currentView`}.form.**`, showPanel: state`app.settings.showErrors` }, function PrettyPrint ({form, showPanel}) { if (!showPanel) { return null } const isValid = isValidForm(form) let invalidFormFields = getInvalidFormFields(form) let result = Object.keys(invalidFormFields).reduce((acc, field) => { const {value} = invalidFormFields[field] acc[field] = { value } return acc }, {}) if (isValid) { result = formToJSON(form) } const resultPane = css( isValid ? styles.successPane : styles.errorPane ) return ( <div className={css(styles.container)}> <div className={resultPane}> {isValid ? 'The form is valid' : 'The form is invalid. See invalid fields below'} </div> <div className={css(styles.innerContainer)}> <pre className={css(styles.pretty)} dangerouslySetInnerHTML={{__html: syntaxHighlight(JSON.stringify(result, undefined, 2))}} /> </div> </div> ) } )
src/components/auth/signin.js
ahmadabugosh/client-react
import React, { Component } from 'react'; import { reduxForm, Field } from 'redux-form'; import { connect } from 'react-redux'; import * as actions from '../../actions'; import { RingLoader } from 'react-spinners'; const renderInput = field => { const { input, type } = field; return ( <div> <input {...input} type={type} className="form-control" /> </div> ); }; export class Signin extends Component { constructor(props) { super(props); } componentWillReceiveProps(props) { // check if there is an errorMessage displayed to the user, // if so, changes isloading(in redux store) to false if (props.errorMessage) { this.props.endLoading(); } } handleFormSubmit({ email, password }) { this.props.beginLoading(); this.props.signinUser({ email, password }, this.props.history); } renderAlert() { if (this.props.errorMessage) { return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } } render() { const { handleSubmit } = this.props; return ( <div> <h1> Sign In To i7san</h1> <div className="container-fluid"> <div className="row"> <div className="col-md-12" id="center"> <h3>Start Tracking Your Volunteering!</h3> <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <div className="form-group"> <label>Email:</label> <Field name="email" type="email" component={renderInput} /> </div> <div className="form-group"> <label>Password:</label> <Field name="password" type="password" component={renderInput} /> </div> {this.renderAlert()} <RingLoader color={'#123abc'} loading={this.props.isLoading} /> <button action="submit" className="btn btn-primary"> Sign in </button> </form> Don't have an account? <a href="/signup">Sign up</a> for Free! </div> </div> <div className="row"> <div className="col-md-4"> <img src= "https://s3.amazonaws.com/i7san-test/svg/planting.svg" alt="Impact" id="side"/> </div> <div className="col-md-4"> <img src= "https://s3.amazonaws.com/i7san-test/svg/volunteer_world.svg" alt="Impact" id="side"/> </div> <div className="col-md-4"> <img src= "https://s3.amazonaws.com/i7san-test/svg/trend.svg" alt="Impact" id="side"/> </div> </div> </div> </div> ); } } function mapStateToProps(state) { return { isLoading: state.isLoading, form: state.form, errorMessage: state.auth.error }; } let connectedSignin = connect(mapStateToProps, actions)(Signin); connectedSignin = reduxForm({ form: 'signin' })(connectedSignin); export default connectedSignin;
Frontend/src/containers/socialauth.js
vinitraj10/Django-React-Blog
import React, { Component } from 'react'; import {withRouter} from 'react-router-dom'; import {connect} from 'react-redux'; //import {loginUsingFb} from '../actions/Authentication/social-auth'; class SocialAuth extends Component{ loadFbLoginApi() { window.fbAsyncInit = function() { FB.init({ appId : '121614955163755', cookie : true, // enable cookies to allow the server to access // the session xfbml : true, // parse social plugins on this page version : 'v2.10' // use version 2.1 }); }; console.log("Loading fb api"); // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } componentDidMount() { this.loadFbLoginApi(); } testAPI() { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Successful login for: ' + response.name); }); } callFbLogin(accessToken,response){ const body ={ "access_token":accessToken }; console.log(response) this.props.loginUsingFb(body,()=>{ this.props.history.push("/"); }); } statusChangeCallback(response) { //console.log('statusChangeCallback'); //console.log(response); const {accessToken} = response.authResponse; if (response.status === 'connected') { this.callFbLogin(accessToken); } else if (response.status === 'not_authorized') { console.log("Please log into this app."); } else { console.log("Please log into this facebook."); } this.callFbLogin(accessToken,response); } checkLoginState() { FB.getLoginStatus(function(response) { this.statusChangeCallback(response); }.bind(this)); } handleFBLogin() { FB.login(this.checkLoginState()); } render(){ return ( <a onClick={this.handleFBLogin.bind(this)} className="btn btn-block btn-fb">Facecbook</a> ) } } SocialAuth = withRouter(SocialAuth); export default connect(null,{loginUsingFb})(SocialAuth); /*<a href="#" onClick={this.handleFBLogin.bind(this)} className="btn btn-block btn-fb">connect with facecbook</a>*/
src/client/components/centered/Centered.js
flute-io/flagshipped-io-app
import React from 'react' import Component from '../component/Component' import './Centered.scss' export default class Centered extends React.Component { render () { return ( <Component class="Centered" {...this}> {this.props.children} </Component> ) } }
packages/interval/src/Component.js
nkbt/react-works
import React from 'react'; import PropTypes from 'prop-types'; export class ReactInterval extends React.Component { static defaultProps = { enabled: false, timeout: 1000 }; static propTypes = { callback: PropTypes.func.isRequired, enabled: PropTypes.bool, timeout: PropTypes.number }; componentDidMount() { const {enabled} = this.props; if (enabled) { this.start(); } } shouldComponentUpdate({timeout, callback, enabled}) { const {timeout: timeout1, callback: callback1, enabled: enabled1} = this.props; return ( timeout1 !== timeout || callback1 !== callback || enabled1 !== enabled ); } componentDidUpdate({enabled, timeout}) { const {timeout: timeout1, enabled: enabled1} = this.props; if (enabled1 !== enabled || timeout1 !== timeout) { if (enabled1) { this.start(); } else { this.stop(); } } } componentWillUnmount() { this.stop(); } callback = () => { if (this.timer) { const {callback} = this.props; callback(); this.start(); } }; start = () => { this.stop(); const {timeout} = this.props; this.timer = setTimeout(this.callback, timeout); }; stop = () => { clearTimeout(this.timer); this.timer = null; }; render = () => false; }
react-log/src/index.js
rod-stuchi/JS-inspect
import React from 'react'; import ReactDOM from 'react-dom'; import { injectGlobal } from 'styled-components'; import App from './App'; injectGlobal` body { font-family: sans-serif; margin: 0; padding: 0; background-color: #d8d8d8; min-width: 700px; overflow-x: hidden; } ::-webkit-scrollbar { width: 3px; height: 3px; } ::-webkit-scrollbar-button { width: 6px; height: 6px; } ::-webkit-scrollbar-thumb { background: #127509; border: 0px none #ffffff; border-radius: 50px; } ::-webkit-scrollbar-thumb:hover { background: #13830a; } ::-webkit-scrollbar-thumb:active { background: #36ef27; } ::-webkit-scrollbar-track { //background: #4a4a4a; background: transparent; border: 0px none #ffffff; border-radius: 50px; } ::-webkit-scrollbar-track:hover { //background: #4a4a4a; background: transparent; } ::-webkit-scrollbar-track:active { //background: #4a4a4a; background: transparent; } ::-webkit-scrollbar-corner { background: transparent; } `; ReactDOM.render( <App />, document.getElementById('root') );
definitions/npm/react-select_v1.x.x/test_react-select_v1.x.x.js
echenley/flow-typed
import React from 'react'; import { default as SelectComponent } from 'react-select'; import type Select from 'react-select'; const ArrowRenderer = (props: { onMouseDown: Event }): React$Element<*> => <span>Arrow</span>; const ClearRenderer = (): React$Element<*> => <span />; const filterOption = (option: Object, filterString: string) => { return true; }; const InputRenderer = (props: Object) => <span />; const MenuRenderer = (props: Object) => [<span />]; const OptionComponent = (props: Object) => <span />; const OptionRenderer = (props: Object) => <span />; const options = [ { value: 123, label: 'first item' }, { value: 345, label: 'second item' }, { value: 'foo', label: 'third item', clearableValue: true }, ]; const ValueComponent = (props: Object) => <span />; const ValueRenderer = (props: Object) => <span />; <SelectComponent addLabelText="Add label, plz" aria-describedby="aria-describedby" aria-label="aria-label" aria-labelledby="aria-labelledby" arrowRenderer={ArrowRenderer} autoBlur={false} autofocus={false} autosize={false} backspaceRemoves={false} backspaceToRemoveMessage="Click backspace to remove" className="my-class-name" clearAllText="Clear all" clearRenderer={ClearRenderer} clearValueText="Clear value" clearable={true} deleteRemoves={false} delimiter="," disabled={false} escapeClearsValue={false} filterOption={filterOption} filterOptions={false} ignoreAccents={false} ignoreCase={false} inputProps={{ someCustomProp: false }} inputRenderer={InputRenderer} instanceId="UNIQUE_ID_HERE" isLoading={false} joinValues={false} labelKey="labelKey" matchPos="start" matchProp="label" menuBuffer={10} menuContainerStyle={{ color: 'green' }} menuRenderer={MenuRenderer} menuStyle={{ color: 'green' }} multi={false} name="fance name" noResultsText="No results found. I'm so terribly sorry. I'll just go now. :´(" onBlur={(event: Event): void => {}} onBlurResetsInput={false} onChange={(value: any): void => {}} onClose={(): void => {}} onCloseResetsInput={false} onFocus={(event: Event) => {}} onInputChange={(value: any) => { return 'foo'; }} onInputKeyDown={(event: Event) => {}} onMenuScrollToBottom={(): void => {}} onOpen={() => {}} onValueClick={(value: string, event: Event) => {}} openAfterFocus={false} openOnFocus={false} optionClassName="fancy-class-for-option" optionComponent={OptionComponent} optionRenderer={OptionRenderer} options={options} pageSize={10} placeholder="Placeholder text" required={false} resetValue={0} scrollMenuIntoView={false} searchable={true} simpleValue={false} style={{ color: 'gray' }} tabIndex={-1} tabSelectsValue={false} value={0} valueComponent={ValueComponent} valueKey="valueKey" valueRenderer={ValueRenderer} wrapperStyle={{ backgroundColor: 'white' }} />; // $ExpectError addLabelText cannot be number <SelectComponent addLabelText={123} />;
packages/material-ui-icons/src/CastConnected.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let CastConnected = props => <SvgIcon {...props}> <path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" /> </SvgIcon>; CastConnected = pure(CastConnected); CastConnected.muiName = 'SvgIcon'; export default CastConnected;
stories/Tooltip/ExampleTheme.js
nirhart/wix-style-react
import React from 'react'; import {Tooltip} from 'wix-style-react'; import styles from './Example.scss'; export default () => <div> <Tooltip active placement="right" alignment="center" content="Dark Theme" showTrigger="custom" hideTrigger="custom" theme="dark"> <div className={styles.box}>Dark Theme</div> </Tooltip> <br/> <Tooltip active placement="right" alignment="center" content="Error Theme" showTrigger="custom" hideTrigger="custom" theme="error"> <div className={styles.box}>Error Theme</div> </Tooltip> </div>;
src/components/common/EditableInput.js
Scratch-it/react-color
'use strict' /* @flow */ import React from 'react' import ReactCSS from 'reactcss' import shallowCompare from 'react-addons-shallow-compare' export class EditableInput extends ReactCSS.Component { shouldComponentUpdate = shallowCompare.bind(this, this, arguments[0], arguments[1]); constructor(props: any) { super() this.state = { value: String(props.value).toUpperCase(), blurValue: String(props.value).toUpperCase(), } } classes(): any { return { 'user-override': { wrap: this.props.style && this.props.style.wrap ? this.props.style.wrap : {}, input: this.props.style && this.props.style.input ? this.props.style.input : {}, label: this.props.style && this.props.style.label ? this.props.style.label : {}, }, 'dragLabel-true': { label: { cursor: 'ew-resize', }, }, } } styles(): any { return this.css({ 'user-override': true, }) } componentWillReceiveProps(nextProps: any) { var input = this.refs.input if (nextProps.value !== this.state.value) { if (input === document.activeElement) { this.setState({ blurValue: String(nextProps.value).toUpperCase() }) } else { this.setState({ value: String(nextProps.value).toUpperCase() }) } } } componentWillUnmount() { this.unbindEventListeners() } handleBlur = () => { if (this.state.blurValue) { this.setState({ value: this.state.blurValue, blurValue: null }) } } handleChange = (e: any) => { if (this.props.label !== null) { var obj = {} obj[this.props.label] = e.target.value this.props.onChange(obj) } else { this.props.onChange(e.target.value) } this.setState({ value: e.target.value }) } handleKeyDown = (e: any) => { var number = Number(e.target.value) if (number) { var amount = this.props.arrowOffset || 1 // Up if (e.keyCode === 38) { if (this.props.label !== null) { var obj = {} obj[this.props.label] = number + amount this.props.onChange(obj) } else { this.props.onChange(number + amount) } this.setState({ value: number + amount }) } // Down if (e.keyCode === 40) { if (this.props.label !== null) { var obj = {} obj[this.props.label] = number - amount this.props.onChange(obj) } else { this.props.onChange(number - amount) } this.setState({ value: number - amount }) } } } handleDrag = (e: any) => { if (this.props.dragLabel) { var newValue = Math.round(this.props.value + e.movementX) if (newValue >= 0 && newValue <= this.props.dragMax) { var obj = {} obj[this.props.label] = newValue this.props.onChange(obj) } } } handleMouseDown = (e: any) => { if (this.props.dragLabel) { e.preventDefault() this.handleDrag(e) window.addEventListener('mousemove', this.handleDrag) window.addEventListener('mouseup', this.handleMouseUp) } } handleMouseUp = () => { this.unbindEventListeners() } unbindEventListeners = () => { window.removeEventListener('mousemove', this.handleChange) window.removeEventListener('mouseup', this.handleMouseUp) } render(): any { var label if (this.props.label) { label = <span is="label" ref="label" onMouseDown={ this.handleMouseDown }>{ this.props.label }</span> } return ( <div is="wrap" ref="container"> <input is="input" ref="input" value={ this.state.value } onKeyDown={ this.handleKeyDown } onChange={ this.handleChange } onBlur={ this.handleBlur }/> { label } </div> ) } } export default EditableInput
webpack/components/TemplateSyncResult/components/SyncedTemplate/StringInfoItem.js
theforeman/foreman_templates
import React from 'react'; import EllipsisWithTooltip from 'react-ellipsis-with-tooltip'; import PropTypes from 'prop-types'; import InfoItem from './InfoItem'; import { itemIteratorId } from './helpers'; const StringInfoItem = ({ template, attr, tooltipText, translate, mapAttr, elipsed, }) => { const inner = ( <span> {translate ? __(mapAttr(template, attr)) : mapAttr(template, attr)} </span> ); const innerContent = elipsed ? ( <EllipsisWithTooltip placement="top">{inner}</EllipsisWithTooltip> ) : ( inner ); return ( <InfoItem itemId={itemIteratorId(template, attr)} tooltipText={tooltipText}> {innerContent} </InfoItem> ); }; StringInfoItem.propTypes = { template: PropTypes.object.isRequired, attr: PropTypes.string.isRequired, tooltipText: PropTypes.string, translate: PropTypes.bool, mapAttr: PropTypes.func, elipsed: PropTypes.bool, }; StringInfoItem.defaultProps = { translate: false, mapAttr: (template, attr) => template[attr], elipsed: false, tooltipText: undefined, }; export default StringInfoItem;
client/src/app/routes/settings/containers/Students/RelativesForm.js
zraees/sms-project
import React from 'react' import { reset } from 'redux-form' import axios from 'axios' import classNames from 'classnames' import { Field, reduxForm } from 'redux-form' import WidgetGrid from '../../../../components/widgets/WidgetGrid' import Datatable from '../../../../components/tables/Datatable' import {RFField, RFReactSelect, RFRadioButtonList } from '../../../../components/ui' import {required, email, number} from '../../../../components/forms/validation/CustomValidation' import AlertMessage from '../../../../components/common/AlertMessage' import {submitStudentRelative, removeStudentRelative} from './submit' import mapForCombo, {isOtherOptionSelected} from '../../../../components/utils/functions' import { upper } from '../../../../components/utils/normalize' import Msg from '../../../../components/i18n/Msg' class RelativesForm extends React.Component { constructor(props){ super(props); this.state = { studentId: 0, classOptions: [], relationOptions: [], activeTab: "add", disabledOtherRelation: true } this.handleOtherRelationBlur = this.handleOtherRelationBlur.bind(this); } componentDidMount(){ instanceAxios.get('/api/lookup/classes/') .then(res=>{ const classOptions = mapForCombo(res.data); this.setState({classOptions}); }); instanceAxios.get('/api/lookup/relations/') .then(res=>{ const relationOptions = mapForCombo(res.data); this.setState({relationOptions}); }); this.setState({studentId: this.props.studentId}); this.props.change('studentId', this.props.studentId); // function provided by redux-form $('#relativesGrid').on('click', 'td', function(event) { if ($(this).find('#dele').length > 0) { //alert( $(this).find('#dele').data('tid')); var id = $(this).find('#dele').data('tid'); removeStudentRelative(id, $(this)); } }); } handleOtherRelationBlur(obj, value){ if(isOtherOptionSelected(value)){ this.setState({disabledOtherRelation:true}); } else{ this.setState({disabledOtherRelation:false}); } } // render() { const { handleSubmit, pristine, reset, submitting, touched, error, warning } = this.props const { studentId, activeTab, classOptions, relationOptions, disabledOtherRelation } = this.state; return ( <WidgetGrid> <div className="tabbable tabs"> <ul className="nav nav-tabs"> <li id="tabAddLink" className="active"> <a id="tabAddRelative" data-toggle="tab" href="#A1A1A"><Msg phrase="AddText" /></a> </li> <li id="tabListLink"> <a id="tabListRelative" data-toggle="tab" href="#B1B1B"><Msg phrase="ListText" /></a> </li> </ul> <div className="tab-content"> <div className="tab-pane active" id="A1A1A"> <form id="form-relative" className="smart-form" onSubmit={handleSubmit((values)=>{submitStudentRelative(values, studentId)})}> <fieldset> <div className="row"> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> <Field name="studentName" labelClassName="input" labelIconClassName="icon-append fa fa-user" validate={required} component={RFField} normalize={upper} maxLength="50" type="text" placeholder="" label="RelativeStudentNameText" /> </section> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> </section> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> </section> </div> <div className="row"> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> <Field multi={false} name="classId" validate={required} label="ClassText" options={classOptions} component={RFReactSelect} /> </section> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> <Field multi={false} name="relationId" validate={required} label="RelationText" options={relationOptions} onBlur={this.handleOtherRelationBlur} component={RFReactSelect} /> </section> <section className="remove-col-padding col-sm-4 col-md-4 col-lg-4"> <Field name="otherRelation" labelClassName="input" labelIconClassName="icon-append fa fa-graduation-cap" component={RFField} disabled={disabledOtherRelation} maxLength="150" type="text" label="OtherRelationText" placeholder=""/> </section> </div> {(error!==undefined && <AlertMessage type="w" icon="alert-danger" message={error} />)} <Field component="input" type="hidden" name="studentId" /> <footer> <button type="button" disabled={pristine || submitting} onClick={reset} className="btn btn-primary"> <Msg phrase="ResetText"/> </button> <button type="submit" disabled={pristine || submitting} className="btn btn-primary"> <Msg phrase="SaveText"/> </button> </footer> </fieldset> </form> </div> <div className="tab-pane table-responsive" id="B1B1B"> <Datatable id="relativesGrid" options={{ ajax: {"url": getWebApiRootUrl() +'/api/StudentsRelatives/All/' + studentId, "dataSrc": ""}, columnDefs: [ { "render": function ( data, type, row ) { return '<a id="dele" data-tid="' + data + '"><i class=\"glyphicon glyphicon-trash\"></i><span class=\"sr-only\">Edit</span></a>'; }.bind(self), "className": "dt-center", "sorting": false, "targets": 3 } ], columns: [ {data: "StudentName"}, {data: "ClassName"}, {data: "Relation"}, {data: "StudentRelativeID"} ], buttons: [ 'copy', 'excel', 'pdf' ] }} paginationLength={true} className="table table-striped table-bordered table-hover" width="100%"> <thead> <tr> <th data-hide="mobile-p"><Msg phrase="StudentNameText"/></th> <th data-hide="mobile-p"><Msg phrase="ClassText"/></th> <th data-hide="mobile-p"><Msg phrase="RelationText"/></th> <th data-hide="mobile-p"></th> </tr> </thead> </Datatable> </div> </div> </div> </WidgetGrid> ) } } const afterSubmit = function(result, dispatch) { dispatch(reset('RelativesForm')); } export default reduxForm({ form: 'RelativesForm', // a unique identifier for this form onSubmitSuccess: afterSubmit, keepDirtyOnReinitialize: false })(RelativesForm)
src/components/Card.js
drakang4/creative-project-manager
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const Wrapper = styled.div` background-color: #ffffff; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); display: flex; flex-direction: ${props => props.direction}; justify-content: center; align-items: center; `; const Card = ({ children, direction }) => { return ( <Wrapper direction={direction}> {children} </Wrapper> ); }; Card.propTypes = { children: PropTypes.node, direction: PropTypes.oneOf(['column', 'row']), }; Card.defaultProps = { direction: 'column', }; export default Card;
react-native/rntwond/__tests__/index.android.js
tung1404/react-courses
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
app/javascript/mastodon/components/status_content.js
tootsuite/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; import PollContainer from 'mastodon/containers/poll_container'; import Icon from 'mastodon/components/icon'; import { autoPlayGif } from 'mastodon/initial_state'; const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top) export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, showThread: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, collapsable: PropTypes.bool, onCollapsedToggle: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; if (!node) { return; } const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } if (this.props.status.get('collapsed', null) === null) { let collapsed = this.props.collapsable && this.props.onClick && node.clientHeight > MAX_HEIGHT && this.props.status.get('spoiler_text').length === 0; if(this.props.onCollapsedToggle) this.props.onCollapsedToggle(collapsed); this.props.status.set('collapsed', collapsed); } } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/@${mention.get('acct')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, ''); if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/tags/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; let element = e.target; while (element) { if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') { return; } element = element.parentNode; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const renderReadMore = this.props.onClick && status.get('collapsed'); const renderViewThread = this.props.showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']); const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, 'status__content--with-spoiler': status.get('spoiler_text').length > 0, 'status__content--collapsed': renderReadMore, }); const showThreadButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick}> <FormattedMessage id='status.show_thread' defaultMessage='Show thread' /> </button> ); const readMoreButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'> <FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' fixedWidth /> </button> ); if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/@${item.get('acct')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} className='translate' /> {' '} <button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} dangerouslySetInnerHTML={content} /> {!hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } else if (this.props.onClick) { const output = [ <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div>, ]; if (renderReadMore) { output.push(readMoreButton); } return output; } else { return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } } }
frontend/views/register/index.spec.js
rkovacevic/hapijs-starter
import '../../utils/setupFakeDOM' import React from 'react' import TestUtils from 'react-addons-test-utils' import {shallowRender} from '../../utils/testUtils' import {Register} from '.' import {expect} from 'chai' import {findWithType, findAllWithType, findWithRef} from 'react-shallow-testutils' import {Input, ButtonInput} from 'react-bootstrap' import {spy} from 'sinon' describe('frontend register view', () => { it('renders form', () => { const component = shallowRender(Register, {}) expect(findWithRef(component, 'username')).to.exist expect(findWithRef(component, 'password')).to.exist expect(findWithRef(component, 'repeatPassword')).to.exist expect(findWithType(component, ButtonInput)).to.exist }) it('renders validation errors', () => { const component = shallowRender(Register, { validationErrors: [ { path: 'username', message: 'username error' }, { path: 'password', message: 'password error' }, { path: 'repeatPassword', message: 'repeat password error' } ] }) expect(findWithRef(component, 'username').props.bsStyle).to.equal('error') expect(findWithRef(component, 'username').props.help).to.equal('username error') expect(findWithRef(component, 'password').props.bsStyle).to.equal('error') expect(findWithRef(component, 'password').props.help).to.equal('password error') expect(findWithRef(component, 'repeatPassword').props.bsStyle).to.equal('error') expect(findWithRef(component, 'repeatPassword').props.help).to.equal('repeat password error') }) it('form submit works', () => { const registerUser = spy() const tree = TestUtils.renderIntoDocument(<Register registerUser={registerUser} />) const component = TestUtils.findRenderedComponentWithType(tree, Register) component.refs.username.getInputDOMNode().value = 'testuser' component.refs.password.getInputDOMNode().value = 'testpass' component.refs.repeatPassword.getInputDOMNode().value = 'testpass' TestUtils.Simulate.submit(component.refs.form) expect(registerUser.getCall(0).args[0]).to.deep.equal({ username: 'testuser', password: 'testpass', repeatPassword: 'testpass' }) }) })
client/node_modules/uu5g03/doc/main/client/src/common/no-script-and-unsupported-browser.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import UU5 from 'uu5'; import Data from '../data/app-config-data.js'; import Breadcrumbs from '../bricks/breadcrumbs.js'; export default React.createClass({ mixins: [UU5.Common.BaseMixin, UU5.Common.ElementaryMixin, UU5.Common.VucMixin], statics: { tagName: 'UU5.Doc.NoScriptAndUnsupportedBrowser', vucTitle: Data.noScriptAndUnsupportedBrowser.name, classNames: { main: 'UU5-DemoPages-Common-noScriptAndUnsupportedBrowser' }, defaults: {} }, propTypes: { header: React.PropTypes.any, navigation: React.PropTypes.array }, getDefaultProps() { return { header: null, navigation: null }; }, //@@viewOn:render render(){ var e = document.createElement("script"); e.src = "https://browser-update.org/update.min.js"; document.body.appendChild(e); return ( <UU5.Layout.Root> {this.props.navigation && <Breadcrumbs items={this.props.navigation.concat([{ text: this.props.header }])} />} <UU5.Layout.ContainerCollection header="Kontrola prostředí prohlížeče" parent={this}> <UU5.Layout.Container header="Zakázaný JavaScript"> <UU5.Bricks.Section> <UU5.Bricks.P> V případě, že má uživatel v prohlížeči zakázaný JavaScript a aplikace ke svému fungování JavaScript potřebuje, je vhodné uživatele na tuto skutečnost upozornit namísto toho, aby se mu při spouštění aplikace zobrazila pouze chybová stránka. </UU5.Bricks.P> <UU5.Bricks.P>V následujícím příkladě je ukázáno standardní upozornění na zakázaný JavaScript, vytvořené pomocí tagu <UU5.Bricks.Code content='<noScript>' />. Obsah tagu <UU5.Bricks.Code content='<noScript>' /> se vykreslí pouze v případě, že prohlížeč JavaScript nepodporuje, nebo ho má zakázaný. Pro použití v konkrétní aplikaci je potřeba si upozornění upravit a nastylovat, případně přidat další jazykovou verzi. </UU5.Bricks.P> </UU5.Bricks.Section> <UU5.Bricks.Section header="Příklad"> <UU5.DocKit.Example header="Detekce Javascriptu v prohlížeči" footer={[ { tag: 'UU5.Bricks.P', props: { content: `V příkladu je ukázáno, jak vypadá vizuální případ užití, který se uživateli zobrazí v případě, že má v prohlížeči zakázané použití JavaScriptu nebo prohlížeč JavaScript nepodporuje. Příklad slouží pouze pro demonstraci vzhledu vizuálního případu užití bez nutnosti JavaScript v prohlížeči opravdu zakázat, proto je jeho obsah vložen do komponenty <UU5.Bricks.Code content='UU5.Bricks.Section'/> namísto tagu <UU5.Bricks.Code content='<noScript>'/>, jak by to bylo při reálném použití viz část <strong>Code</strong> níže.` } }, { tag: 'UU5.Bricks.Panel', props: { content: { tag: 'UU5.Bricks.FileViewer', props: { src: './data/examples/exampleNoScript.html', blockKey: '0', numbered: true } }, header: 'Code', glyphiconExpanded: 'glyphicon-menu-up', glyphiconCollapsed: 'glyphicon-menu-down' } }, { tag: 'UU5.Bricks.Panel', props: { content: { tag: 'UU5.Bricks.FileViewer', props: { src: './data/examples/exampleNoScript.html', blockKey: '1', numbered: true } }, header: 'CSS', glyphiconExpanded: 'glyphicon-menu-up', glyphiconCollapsed: 'glyphicon-menu-down' } } ]}> <UU5.Bricks.Iframe src='./data/examples/exampleNoScript.html' resize /> </UU5.DocKit.Example> </UU5.Bricks.Section> </UU5.Layout.Container> <UU5.Layout.Container header="Nepodporovaný prohlížeč"> <UU5.Bricks.Section> <UU5.Bricks.P> Upozornění se zobrazí uživateli, pokud si otevře aplikaci v nepodporovaném prohlížeči a nabídne odkaz na stránku s návody na aktualizaci prohlížeče viz <UU5.Bricks.Link href='https://browser-update.org/' target='_blank' />. Uživatel může nabídku na aktualizaci prohlížeče ignorovat pomocí tlačítka, které je součástí upozornění. </UU5.Bricks.P> <UU5.Bricks.P> Kód zobrazující upozornění pro konkrétní prohlížeče je možné vygenerovat si přímo na stránce <UU5.Bricks.Link href='https://browser-update.org/' target='_blank' />, kde stačí zadat pouze verze prohlížečů, pro které se bude upozorněné zobrazovat a případně upravit i další nastavení. Upozornění samotné se automaticky zobrazí v jazyce uživatele. </UU5.Bricks.P> </UU5.Bricks.Section> <UU5.Bricks.Section header='Podporované prohlížeče'> <UU5.Bricks.Table hover condensed> <UU5.Bricks.Table.THead> <UU5.Bricks.Table.Tr className='bg-info'> <UU5.Bricks.Table.Th content='Prohlížeč' /> <UU5.Bricks.Table.Th content='Nejstarší podporovaná verze' /> </UU5.Bricks.Table.Tr> </UU5.Bricks.Table.THead> <UU5.Bricks.Table.TBody> <UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Th content='Chrome' /> <UU5.Bricks.Table.Td content='31' /> </UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Th content='Firefox' /> <UU5.Bricks.Table.Td content='31' /> </UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Th content='Internet Explorer / Microsoft Edge' /> <UU5.Bricks.Table.Td content='11' /> </UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Th content='Opera' /> <UU5.Bricks.Table.Td content='26' /> </UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Tr> <UU5.Bricks.Table.Th content='Safari' /> <UU5.Bricks.Table.Td content='9' /> </UU5.Bricks.Table.Tr> </UU5.Bricks.Table.TBody> </UU5.Bricks.Table> </UU5.Bricks.Section> <UU5.DocKit.Example header="Example" footer={[ { tag: 'UU5.Bricks.P', props: { content: `Kliknutím na tlačítko se uživateli zobrazí upozornění, které se jinak zobrazuje pouze pokud si uživatel otevře aplikaci v nepodporovaném prohlížeči.` } }, { tag: 'UU5.Bricks.Panel', props: { content: { tag: 'UU5.Bricks.FileViewer', props: { src: './data/examples/exampleUnsupportedBrowser.html', blockKey: '0', numbered: true } }, header: 'Code', glyphiconExpanded: 'glyphicon-menu-up', glyphiconCollapsed: 'glyphicon-menu-down' } }, ]}> <br /> <UU5.Bricks.Button onClick={ () => $buo({}, true)}> Zobrazit upozornění na podporovaný prohlížeč</UU5.Bricks.Button><br /><br /> </UU5.DocKit.Example> </UU5.Layout.Container> </UU5.Layout.ContainerCollection> </UU5.Layout.Root> ) } //@@viewOn:render })
src/js/components/Posts.spec.js
slavapavlutin/pavlutin-node
import React from 'react'; import render from 'react-test-renderer'; import { MemoryRouter as Router } from 'react-router-dom'; import Posts from './Posts'; const posts = [ { id: 0, title: 'First Post', tags: ['js'] }, { id: 1, title: 'Second Post' }, ]; it('renders posts', () => { const tree = render.create(<Router><Posts posts={posts} /></Router>); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders posts with active tag', () => { const tree = render.create( <Router> <Posts posts={posts} tag="tag" /> </Router>, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders message when there are no posts', () => { const tree = render.create(<Posts posts={[]} />); expect(tree.toJSON()).toMatchSnapshot(); });
src/components/auction/teams/WonPlayer.js
akeely/twoguysandadream-js
import React from 'react'; export default class WonPlayer extends React.Component { render() { var player = this.props.rosterEntry.player; var cost = this.props.rosterEntry.cost; var positions = player.positions .map(function(pos) { return pos.name; }) .join(', '); return ( <tr> <td>{player.name} - <span className="text-muted small">{positions}</span></td> <td>${cost}</td> </tr> ); } }
src/components/common/books/BookShelf.js
zainxyz/react-reads
import PropTypes from 'prop-types'; import React from 'react'; import SectionHeader from 'components/common/typography/SectionHeader'; import BookGrid from './BookGrid'; /** * Render a single bookshelf containing a collection of books * @param {Array} options.booksList The list of books * @param {Function} options.onShelfChange The callback for shelf change event * @param {string} options.title The title of the bookshelf * @param {Object} options The props for the BookShelf component * @return {JSX} */ const BookShelf = ({ booksList, onShelfChange, title, }) => ( <div className="bookshelf"> { title && <SectionHeader className="bookshelf-title" title={title} /> } <div className="bookshelf-books"> { booksList && <BookGrid booksList={booksList} onShelfChange={onShelfChange} viewDetailsLink /> } </div> </div> ); BookShelf.propTypes = { booksList: PropTypes.array.isRequired, onShelfChange: PropTypes.func, title: PropTypes.string.isRequired, }; BookShelf.defaultProps = { onShelfChange: () => {}, }; export default BookShelf;
src/media/js/addon/containers/dashboardDetail.js
diox/marketplace-content-tools
/* Dashboard page for a single add-on. */ import React from 'react'; import {connect} from 'react-redux'; import {ReverseLink} from 'react-router-reverse'; import {bindActionCreators} from 'redux'; import AddonVersionListingContainer from './versionListing'; import {changeSlug, fetch as fetchAddon} from '../actions/addon'; import {del as deleteAddon} from '../actions/dashboard'; import {messageChange, submitVersion} from '../actions/submitVersion'; import {Addon, AddonIcon, AddonForDashboardDetail} from '../components/addon'; import SlugChange from '../components/slugChange'; import AddonSubnav from '../components/subnav'; import AddonUpload from '../components/upload'; import ConfirmButton from '../../site/components/confirmButton'; import {Page, PageSection} from '../../site/components/page'; export class AddonDashboardDetail extends React.Component { static contextTypes = { store: React.PropTypes.object }; static propTypes = { addon: React.PropTypes.object, fetchAddon: React.PropTypes.func.isRequired, deleteAddon: React.PropTypes.func.isRequired, isSubmitting: React.PropTypes.bool, messageChange: React.PropTypes.func.isRequired, slug: React.PropTypes.string.isRequired, submit: React.PropTypes.func.isRequired, uploadLoaded: React.PropTypes.number, uploadTotal: React.PropTypes.number, user: React.PropTypes.object, validationError: React.PropTypes.string, }; constructor(props) { super(props); this.props.fetchAddon(this.props.slug); } handleDelete = () => { this.props.deleteAddon(this.props.addon.slug); } renderDeleted() { return ( <PageSection> <p> This add-on has been deleted. <ReverseLink to="addon-dashboard"> Return to My Add-ons</ReverseLink> </p> </PageSection> ); } render() { if (!this.props.addon || !this.props.addon.slug) { return ( <Page subnav={<AddonSubnav user={this.props.user}/>} title="Loading Firefox OS Add-on..."/> ); } const title = ( <div className="addon-page-title"> <AddonIcon icons={this.props.addon.icons}/> {this.props.addon.name} </div> ); return ( <Page breadcrumbText="My Add-ons" breadcrumbTo="addon-dashboard" className="addon-dashboard-detail" subnav={<AddonSubnav user={this.props.user}/>} title={title}> {this.props.addon.deleted && this.renderDeleted()} {!this.props.addon.deleted && <div> <AddonForDashboardDetail className="addon-dashboard-detail--versions" showDeveloperActions={true} {...this.props.addon}/> <AddonVersionListingContainer className="addon-dashboard-detail--versions" showDeveloperActions={true}/> <PageSection title="Upload a New Version"> <AddonUpload {...this.props}/> </PageSection> <PageSection title="Available Actions" className="addon-dashboard-detail--actions"> <p>You can perform the following actions on this add-on:</p> <ul> <li> <SlugChange addonId={this.props.addon.id} changeSlug={this.props.changeSlug} error={this.props.addon.changeSlugError} isProcessing={this.props.addon.isChangingSlug} slug={this.props.addon.slug}/> </li> <li> <ConfirmButton className="button--delete" initialText="Delete add-on" onClick={this.handleDelete} processingText="Deleting add-on&hellip;"/> <p> Deleting your add-on will permanently delete it from Marketplace. There is no going back. </p> </li> </ul> </PageSection> </div> } </Page> ); } }; export default connect( state => ({ ...state.addonSubmitVersion, addon: state.addon.addons[state.router.params.slug], slug: state.router.params.slug, }), dispatch => bindActionCreators({ changeSlug, fetchAddon, deleteAddon, messageChange, submit: submitVersion }, dispatch) )(AddonDashboardDetail);