path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
Js/Ui/Components/Data/index.js
Webiny/Webiny
import React from 'react'; import _ from 'lodash'; import Webiny from 'webiny'; /** * @i18n.namespace Webiny.Ui.Data */ class Data extends Webiny.Ui.Component { constructor(props) { super(props); this.autoRefreshInterval = null; // Ony when 'autoRefresh' prop is used this.state = { data: null, initiallyLoaded: false }; this.bindMethods('setData,load'); Webiny.Mixins.ApiComponent.extend(this); } componentWillMount() { super.componentWillMount(); this.setState({loading: true}); } componentDidMount() { super.componentDidMount(); this.request = this.api.execute().then(apiResponse => { if (!this.isMounted()) { return null; } this.setData(apiResponse); this.setState({initiallyLoaded: true}); this.props.onInitialLoad(apiResponse); return apiResponse.getData(); }); if (_.isNumber(this.props.autoRefresh)) { this.autoRefreshInterval = setInterval(() => { this.request = this.api.execute().then(response => { this.setData(response); return response.getData(); }); }, this.props.autoRefresh * 1000); } } componentWillUnmount() { super.componentWillUnmount(); if (this.request) { this.request.cancel(); } if (this.autoRefreshInterval) { clearInterval(this.autoRefreshInterval); } } setData(response) { this.request = null; if (response.isAborted() || !this.isMounted()) { return; } if (response.isError()) { this.setState({loading: false}); Webiny.Growl.info(response.getError(), this.i18n('Could not fetch data'), true); return; } this.setState({data: this.props.prepareLoadedData({data: response.getData()}), loading: false}); } load(filters = {}) { this.setState({loading: true}); this.request = this.api.setQuery(filters).execute().then(apiResponse => { if (!this.isMounted()) { return; } this.setData(apiResponse); this.props.onLoad(apiResponse); }); return this.request; } } Data.defaultProps = { waitForData: true, autoRefresh: null, onLoad: _.noop, onInitialLoad: _.noop, prepareLoadedData: ({data}) => data, renderer() { if (!_.isFunction(this.props.children)) { throw new Error('Warning: Data component only accepts a function as its child element!'); } if (this.props.waitForData && this.state.data === null) { return null; } const {Loader} = this.props; const loader = this.state.loading ? <Loader/> : null; return ( <webiny-data> {this.props.children.call(this, { data: _.cloneDeep(this.state.data), load: this.load, loader: loader, $this: this })} </webiny-data> ); } }; export default Webiny.createComponent(Data, {modules: ['Loader']});
stories/index.js
sm-react/storybook-chapters
/* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable react/jsx-filename-extension */ import React from 'react'; import { storiesOf, getStorybook } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, text } from '@storybook/addon-knobs'; import { jumpTo } from '../src'; import Button from './button'; /** note: decorators * You can add decorator globally: * addDecorator(muiTheme(greyTheme)); * You can pass a single object or an array of themes */ const bookmarks = {}; const fn = (num, bm) => () => ( <div> <h4>Custom Component {num}</h4> <button onClick={bm ? bookmarks[bm] : action(`Story number #${num}`)}> Press me {num} times </button> </div> ); const select = { set1: () => {}, set2: () => {}, go1() { // select.set1(false); return () => { return (<button onClick={() => select.set1(false)}>set1 on</button>); }; }, go2() { return () => { // select.set2(true); return (<button onClick={() => select.set2(true)}>set2 on</button>); }; }, }; storiesOf('.addChapter API 🔖', module) .addChapter('Atoms with bookmarks', chapter => chapter .add('Atom 1 with bookmarks.at1', fn(1)) .bookmark((bm) => { bookmarks.at1 = bm; }) .add('Atom 2 bookmarks.at2', fn(2)) .bookmark((bm) => { bookmarks.at2 = bm; }) .add('Bookmark To Atom1', () => ( <div> <p>{'Use bookmark: onClick={bookmarks.at1}'}</p> <button onClick={bookmarks.at1}> Go </button> </div> )) .add('Bookmark To Atom2', () => ( <div> <p>{'Use bookmark: onClick={bookmarks.at2}'}</p> <button onClick={bookmarks.at2}> Go </button> </div> )) .add('Bookmark To Right Panel', () => ( <div> <p>{'Use bookmark: onClick={bookmarks.rgt}'}</p> <button onClick={bookmarks.rgt}> Go </button> </div> )) .add('Jump To Organism 1', () => ( <div> <p>{"Use jumpTo: onClick={jumpTo('Organisms', 'Organism 1')}"}</p> <button onClick={jumpTo('Organisms', 'Organism 1')}> Go </button> </div> )) .bookmarkList() .addChapter('Molecules', chapter => chapter .addChapter('Organisms', chapter => chapter .add('Organism 1', fn(7)) .add('Organism 2', fn(8)), ) .addWithInfo('Molecule 1', fn(1)) .addWithInfo('Molecule 2', fn(2)), ) .add('Atom 3', fn(3)) .add('Atom 4', fn(4)), ) .add('choose Dark side', () => { select.set1(false); select.set2(); return (<div>{'select.set1(false) -> Heroes Dark'}</div>); }) .add('choose Light side', () => { select.set1(); select.set2(false); return (<div>{'select.set2(false) -> Heroes Light'}</div>); }); storiesOf('.chapter API', module) .storyDecorator(withKnobs) .chapter('Left panel') .chapter('Bottom Panel') .add('Input 3', () => <span>[3]: {text('[3]', '33')}</span>) .add('Input 4', () => <span>[4]: {text('[4]', '44')}</span>) .endOfChapter() .chapter('Header Panel') .addWithInfo('Input 5', fn(5)) .addWithInfo('Input 6', fn(6), { inline: true }) .endOfChapter() .endOfChapter() .chapter('Right panel') .bookmark((bm) => { bookmarks.rgt = bm; }) .add('Button 7', fn(7)) .bookmark((bm) => { bookmarks.But7 = bm; }) .add('Button 8', fn(8, 'But7')) .add('Bookmark', fn(8, 'atoms')) .bookmarkList() .endOfChapter() .add('Dark side', () => { select.set1(false); select.set2(); return (<div>{'select.set1(false)'}</div>); }) .add('Light side', () => { select.set1(); select.set2(false); return (<div>{'select.set2(false)'}</div>); }) .add('App footer', fn(110)); storiesOf('Heroes Light', module) .disable((en) => { select.set1 = en; }) .add('Light 1', fn(0)) .add('Light 2', fn(0)) .add('Light 3', fn(0)) .add('Light 4', fn(0)); storiesOf('Heroes Dark', module) .enable((en) => { select.set2 = en; }) .add('Dark 1', fn(0)) .add('Dark 2', fn(0)) .add('Dark 3', fn(0)) .add('Dark 4', fn(0)); storiesOf('Mixed API', module) .addChapter('Atoms new', chapter => chapter .add('Atom 1', fn(1)) .bookmark((bm) => { bookmarks.Atom1 = bm; }) .add('Atom 2', fn(2, 'Atom1')) .addChapter('Molecules new', chapter => chapter .chapter('Cells old') .add('Cell 1', fn(1)) .add('Cell 2', fn(2)) .addChapter('Organisms new in old', chapter => chapter .add('Organism 1', fn(1)) .add('Organism 2', fn(2)), ) .endOfChapter() .add('Molecule 1', fn(1)) .add('Molecule 2', fn(2)), ) .add('Atom 3', fn(3)) .add('Atom 4', fn(4)), ) .add('new API docs', fn(3)) .add('prev API docs', fn(4)); // console.log(getStorybook());
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
nauzethc/react-router
import React from 'react'; class Assignment extends React.Component { render () { var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
packages/material-ui-icons/src/NetworkLocked.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M19.5 10c.17 0 .33.03.5.05V1L1 20h13v-3c0-.89.39-1.68 1-2.23v-.27c0-2.48 2.02-4.5 4.5-4.5zm2.5 6v-1.5c0-1.38-1.12-2.5-2.5-2.5S17 13.12 17 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z" /></g> , 'NetworkLocked');
template/src/components/Hello.js
phonegap/phonegap-template-react-hot-loader
import React from 'react'; import Tappable from 'react-tappable'; import '../css/hello.css'; import Message from './Message'; const Hello = React.createClass({ displayName: 'Hello', getInitialState() { return { message: '', }; }, sayHello(msg) { // CSSTransitionGroup will fade this in this.setState({ message: msg }); setTimeout(() => { // CSSTransitionGroup will now fade this out this.setState({ message: '', }); }, 2000); }, render() { return ( <div className="hello"> <Message message={ this.state.message } /> <Tappable className="button-say-hello" onTap={ () => this.sayHello('Hello world') } >Say hello</Tappable> </div> ); }, }); module.exports = Hello;
generators/app/templates/_app/_app.js
sajal50/generator-reactredux
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import store from './store/store.js'; ReactDOM.render( <Provider store = {store}> <div> Create something awesome. </div> </Provider> ,document.getElementById('app'));
src/components/Label.js
robwalkerco/caerurfapugs
import React from 'react' import styled from 'styled-components' export default styled.label` display: block; `
packages/watif-tutorial/src/index.js
jwillesen/watif
import React from 'react' export function initialize(universe) { universe.addLogEntry( <text> Now that you're here, you're not sure whether it was a good idea to house sit for a week, but here you are, standing in front of the house. </text> ) universe.setStateOf('player', {location: 'front-porch'}) }
src/components/lmap.js
opsukka/fantasy-map
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Map, TileLayer, Marker, Popup, ZoomControl, PropTypes as MapPropTypes } from 'react-leaflet'; import L from 'leaflet'; import { db } from '../firebase/firebase.js'; import data from './markers.json'; const MyPopupMarker = ({ children, position }) => ( <Marker position={position}> <Popup> <span>{children}</span> </Popup> </Marker> ) MyPopupMarker.propTypes = { children: MapPropTypes.children, position: MapPropTypes.latlng, } var myIcon = L.icon({ iconUrl: '../marker-icon.png', iconSize: [26, 41] }); const MyMarkersList = ({ markers }) => { const items = markers.map(({ key, position, children }) => ( <MyPopupMarker key={key} position={position} icon={L.icon} children={children} /> )) return <div style={{ display: 'none',}}>{items}</div> } MyMarkersList.propTypes = { markers: PropTypes.array.isRequired, } export default class VMap extends React.Component { constructor(props) { super(props); animate: true, this.refmarker = React.createRef(), this.state = { center: [0, 0], players: [0, 0], zoom: 4, } } componentDidMount() { db.ref().child(`position/players`).on('value', snap => { this.setState({ players: snap.val() }); }); } updatePosition = () => { const { lat, lng } = this.refmarker.current.leafletElement.getLatLng() db.ref().child(`position/players`).set({ lat, lng }) // this.setState({ // marker: { lat, lng }, // }) this.refmarker.current.leafletElement.getPopup().setContent('Clicked ' + this.refmarker.current.leafletElement.getLatLng()) } render() { const markers = data.markers const view = this.props.position return ( <Map zoomControl={false} center={view} zoom={this.state.zoom} maxZoom={5} minZoom={2} length={10} animate={true}> <panTo /> <TileLayer maxZoom={5} minZoom={2} noWrap={true} attribution="&amp;copy <a href=&quot;https://github.com/opsukka&quot;>Zukop</a> contributors" url="https://firebasestorage.googleapis.com/v0/b/fantasy-map.appspot.com/o/valcia%2F{z}%2F{x}%2F{y}.png?alt=media" /> <ZoomControl position="topright" /> <Marker draggable={true} onDragend={this.updatePosition} position={this.state.players} ref={this.refmarker}> <Popup minWidth={50}> <span> Players </span> </Popup> </Marker> <MyMarkersList markers={ markers } /> </Map> ) } }
docs/src/app/components/pages/components/FlatButton/ExampleSimple.js
verdan/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; const FlatButtonExampleSimple = () => ( <div> <FlatButton label="Default" /> <FlatButton label="Primary" primary={true} /> <FlatButton label="Secondary" secondary={true} /> <FlatButton label="Disabled" disabled={true} /> </div> ); export default FlatButtonExampleSimple;
src/layers/LayerGroup.js
FourwingsY/react-sketch-viewer
import React from 'react' import PropTypes from 'prop-types' import Color from '../data/Color' import {getPositionStyle} from '../utils/layerUtils' class LayerGroup extends React.Component { static propTypes = { layer: PropTypes.object, } static contextTypes = { renderLayer: PropTypes.func, } render() { const layer = this.props.layer const {name, background, layers: childLayers} = layer const style = { ...getPositionStyle(layer), background: (new Color(background)).getRgba() } return ( <div className='group' data-sketch-name={name} style={style}> {childLayers.map(this.context.renderLayer)} </div> ) } } export default LayerGroup
src/components/TextInput.js
MeMark2/sample-react-project
import React from 'react' import ReactDOM from 'react-dom' export default React.createClass({ focusText() { ReactDOM.findDOMNode(this.refs.textArea).focus() }, render() { let type = 'text' if (this.props.password) { type = 'password' } return ( <div className='textInput' onClick={this.focusText}> <img className='textInput__icon' src={this.props.iconSrc}/> <input ref='textArea' type={type} placeholder={this.props.placeholder} className='textInput__input' onBlur={this.props.onLoseFocus} onChange={this.props.onTextChange}/> </div> ) } })
src/Label.js
tonylinyy/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Label = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render() { let classes = this.getBsClassSet(); return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Label;
app/components/Searchahead/index.js
ninjaref/ninjaref
import React from 'react'; import PropTypes from 'prop-types'; import { Form, FormGroup, Label } from 'reactstrap'; import { withRouter } from 'react-router'; import Select from 'react-select'; import axios from 'axios'; class Searchahead extends React.Component { static propTypes = { history: PropTypes.object.isRequired, } constructor(props) { super(props); this.state = { suggestions: [], }; this.handleChange = this.handleChange.bind(this); } componentDidMount() { axios.get('http://localhost:9000/v1/ninjas') .then((res) => { this.setState({ suggestions: this.fixNames(res.data.data) }); }); } handleChange(val) { this.props.history.push(`/profile/${val.ID}`); } /* eslint-disable no-param-reassign */ fixNames(data) { data.forEach((item, index) => { data[index].Name = `${item.FirstName} ${item.LastName}`; }); return data; } /* eslint-enable no-param-reassign */ render() { return ( <Form> <FormGroup> <Label for="query">Get started by entering a competitor&#39;s name:</Label> <Select name="form-field-name" valueKey="Name" labelKey="Name" options={this.state.suggestions} onChange={this.handleChange} /> </FormGroup> </Form> ); } } export default withRouter(Searchahead);
storybook/stories/bar-chart/index.js
JesperLekland/react-native-svg-charts
import React from 'react' import { storiesOf } from '@storybook/react-native' import Standard from './standard' import Horizontal from './horizontal' import Grouped from './grouped' import GroupedHorizontal from './horizontal-grouped' import WithGradient from './with-gradient' import WithYMinMax from './with-y-min-max' import WithOnPress from './with-on-press' import ShowcaseCard from '../showcase-card' storiesOf('BarChart', module) .addDecorator((getStory) => <ShowcaseCard>{getStory()}</ShowcaseCard>) .add('Standard', () => <Standard />) .add('Grouped', () => <Grouped />) .add('Horizontal', () => <Horizontal />) .add('Horizontal - grouped', () => <GroupedHorizontal />) .add('With onPress', () => <WithOnPress />) .add('With gradient', () => <WithGradient />) .add('With ymin/max', () => <WithYMinMax />)
src/svg-icons/action/perm-scan-wifi.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermScanWifi = (props) => ( <SvgIcon {...props}> <path d="M12 3C6.95 3 3.15 4.85 0 7.23L12 22 24 7.25C20.85 4.87 17.05 3 12 3zm1 13h-2v-6h2v6zm-2-8V6h2v2h-2z"/> </SvgIcon> ); ActionPermScanWifi = pure(ActionPermScanWifi); ActionPermScanWifi.displayName = 'ActionPermScanWifi'; ActionPermScanWifi.muiName = 'SvgIcon'; export default ActionPermScanWifi;
src/svg-icons/communication/phonelink-erase.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhonelinkErase = (props) => ( <SvgIcon {...props}> <path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z"/> </SvgIcon> ); CommunicationPhonelinkErase = pure(CommunicationPhonelinkErase); CommunicationPhonelinkErase.displayName = 'CommunicationPhonelinkErase'; export default CommunicationPhonelinkErase;
src/primitives/container/flex-container/index.js
mpigsley/sectors-without-number
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import './style.scss'; export default function FlexContainer({ align, className, justify, direction, children, wrap, scroll, flex, shrink, style, ...rest }) { const containerStyle = flex !== null ? { ...style, flex } : style; return ( <div {...rest} style={containerStyle} className={classNames('FlexContainer', className, { [`FlexContainer-Align--${align}`]: align, [`FlexContainer-Justify--${justify}`]: justify, [`FlexContainer-Direction--${direction}`]: direction, [`FlexContainer-Shrink--${shrink}`]: shrink, 'FlexContainer-Wrap': wrap, 'FlexContainer-Scroll': scroll, })} > {children} </div> ); } FlexContainer.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, align: PropTypes.oneOf([ 'stretch', 'center', 'flexStart', 'flexEnd', 'baseline', 'initial', 'inherit', ]), justify: PropTypes.oneOf([ 'flexStart', 'flexEnd', 'center', 'spaceBetween', 'spaceAround', 'spaceEvenly', 'initial', 'inherit', ]), direction: PropTypes.oneOf(['row', 'column']), wrap: PropTypes.bool, scroll: PropTypes.bool, flex: PropTypes.string, shrink: PropTypes.oneOf(['0', '1']), style: PropTypes.shape(), }; FlexContainer.defaultProps = { className: null, align: 'stretch', justify: null, direction: null, wrap: false, scroll: false, flex: null, shrink: null, style: {}, };
src/components/Touchable/index.js
r1cebank/react-native-boilerplate
import React from 'react'; import { TouchableHighlight, TouchableNativeFeedback, Platform } from 'react-native'; function F8TouchableIOS(props) { return ( <TouchableHighlight accessibilityTraits="button" underlayColor="#3C5EAE" {...props} /> ); } const F8Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : F8TouchableIOS; module.exports = F8Touchable;
app/app.js
castlemilk/nutry-web
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved, import/extensions */ // Load the manifest.json file and the .htaccess file import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/css/bootstrap-theme.css'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; // const injectTouchTapEvent = require('react-tap-event-plugin'); // injectTouchTapEvent(); import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import LanguageProvider from 'containers/LanguageProvider'; import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
src/components/RectangleManipulationControls.js
tmpaul06/gathering-client
import React from 'react'; export default class RectangleManipulationControls extends React.Component { constructor(props) { super(props); this.state = { initialX: 0, initialY: 0, rotate: 0 }; this.handleKeyDown = this.handleKeyDown.bind(this); } componentWillMount() { document.addEventListener('keydown', this.handleKeyDown); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyDown); } render() { return ( <div className='rectangle-controls'> {/*<div className='direction-controls'> {[ 'up', 'right', 'down', 'left' ].map((direction, i) => { return (<div key={i} onClick={() => this.props.move(direction)} className={'direction-control ' + direction}> {direction.toUpperCase()} </div>); })} </div>*/} <div className='circle-control'> <div className='arc-handle' style={{ transform: 'rotate(' + (this.state.rotate + 60) + 'deg) skewX(30deg)' }}> </div> </div> </div> ); } handleKeyDown(e) { let code = e.keyCode || e.which; let direction; if (code === 38) { // up direction = 'up'; } else if (code === 40) { // down direction = 'down'; } else if (code === 37) { // left direction = 'left'; } else if (code === 39) { // right direction = 'right'; } if (direction) { return this.props.onMove(direction); } if (code === 74) { this.setState({ rotate: this.state.rotate - 3 }); this.props.onRotate(this.state.rotate - 3); } else if (code === 75) { this.setState({ rotate: this.state.rotate + 3 }); this.props.onRotate(this.state.rotate + 3); } } }
shorten_my_link/client/components/link_list.js
saitai0802/meteor-basic
import React, { Component } from 'react'; import { createContainer } from 'meteor/react-meteor-data'; import { Links } from '../../imports/collections/links'; class LinkList extends Component { renderRows() { return this.props.links.map(link => { const { url, clicks, token } = link; // I created this server with 3001 port. const shortLink = `http://localhost:3001/${token}`; //ES6 template string format return ( <tr key={token}> <td>{url}</td> <td> <a href={shortLink} target="_blank">{shortLink}</a> </td> <td> {clicks} </td> </tr> ); }); } render() { return ( <table className="table"> <thead> <tr> <th>URL</th> <th>Address</th> <th>Clicks</th> </tr> </thead> <tbody> {this.renderRows()} </tbody> </table> ); } } // export default LinkList; // Remember to use container when everytime we are consuming a publication // with a subscription into a container. export default createContainer(() => { Meteor.subscribe('links'); // You may find links publication in /server/main.js return { links: Links.find({}).fetch() }; }, LinkList);
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js
Ajunboys/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ContactStore from 'stores/ContactStore'; import ContactActionCreators from 'actions/ContactActionCreators'; import AddContactStore from 'stores/AddContactStore'; import AddContactActionCreators from 'actions/AddContactActionCreators'; import ContactsSectionItem from './ContactsSectionItem.react'; import AddContactModal from 'components/modals/AddContact.react.js'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { isAddContactModalOpen: AddContactStore.isModalOpen(), contacts: ContactStore.getContacts() }; }; class ContactsSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { ContactActionCreators.hideContactList(); ContactStore.removeChangeListener(this.onChange); AddContactStore.removeChangeListener(this.onChange); } constructor(props) { super(props); this.state = getStateFromStores(); ContactActionCreators.showContactList(); ContactStore.addChangeListener(this.onChange); AddContactStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } onChange = () => { this.setState(getStateFromStores()); }; openAddContactModal = () => { AddContactActionCreators.openModal(); }; render() { let contacts = this.state.contacts; let contactList = _.map(contacts, (contact, i) => { return ( <ContactsSectionItem contact={contact} key={i}/> ); }); let addContactModal; if (this.state.isAddContactModalOpen) { addContactModal = <AddContactModal/>; } return ( <section className="sidebar__contacts"> <ul className="sidebar__list sidebar__list--contacts"> {contactList} </ul> <footer> <RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/> {addContactModal} </footer> </section> ); } } export default ContactsSection;
modules/Lifecycle.js
bs1180/react-router
import React from 'react' import invariant from 'invariant' const { object } = React.PropTypes /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ const Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount() { invariant( this.routerWillLeave, 'The Lifecycle mixin requires you to define a routerWillLeave method' ) const route = this.props.route || this.context.route invariant( route, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin' ) this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute( route, this.routerWillLeave ) }, componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute() } } export default Lifecycle
client/index.js
sergiokopplin/react-universally
/* eslint-disable global-require */ import React from 'react'; import { render } from 'react-dom'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import asyncBootstrapper from 'react-async-bootstrapper'; import { AsyncComponentProvider } from 'react-async-component'; import './polyfills'; import ReactHotLoader from './components/ReactHotLoader'; import DemoApp from '../shared/components/DemoApp'; // Get the DOM Element that will host our React application. const container = document.querySelector('#app'); // Does the user's browser support the HTML5 history API? // If the user's browser doesn't support the HTML5 history API then we // will force full page refreshes on each page change. const supportsHistory = 'pushState' in window.history; // Get any rehydrateState for the async components. // eslint-disable-next-line no-underscore-dangle const asyncComponentsRehydrateState = window.__ASYNC_COMPONENTS_REHYDRATE_STATE__; /** * Renders the given React Application component. */ function renderApp(TheApp) { // Firstly, define our full application component, wrapping the given // component app with a browser based version of react router. const app = ( <ReactHotLoader> <AsyncComponentProvider rehydrateState={asyncComponentsRehydrateState}> <BrowserRouter forceRefresh={!supportsHistory}> <TheApp /> </BrowserRouter> </AsyncComponentProvider> </ReactHotLoader> ); // We use the react-async-component in order to support code splitting of // our bundle output. It's important to use this helper. // @see https://github.com/ctrlplusb/react-async-component asyncBootstrapper(app).then(() => render(app, container)); } // Execute the first render of our app. renderApp(DemoApp); // This registers our service worker for asset caching and offline support. // Keep this as the last item, just in case the code execution failed (thanks // to react-boilerplate for that tip.) require('./registerServiceWorker'); // The following is needed so that we can support hot reloading our application. if (process.env.BUILD_FLAG_IS_DEV === 'true' && module.hot) { // Accept changes to this file for hot reloading. module.hot.accept('./index.js'); // Any changes to our App will cause a hotload re-render. module.hot.accept('../shared/components/DemoApp', () => { renderApp(require('../shared/components/DemoApp').default); }); }
stories/index.js
yuchi/react-faceted-token-input
import React, { Component } from 'react'; import { storiesOf } from '@kadira/storybook'; import * as TokenTypes from './types'; import { RESULTS } from './types/result-field-token-type'; import FacetedTokenInput from '../src/FacetedTokenInput'; const componentClasses = { wrapper: 'test1', input: 'test2', tokenWrapper: 'test3', token: 'test4', facet: 'test5', description: 'test6', dropdownWrap: 'test7', dropdownUl: 'test8', dropdownLi: 'test9', dropdownA: 'test10', suggestionsWrap: 'test11', suggestionsUl: 'test12', suggestionsLi: 'test13', suggestionsA: 'test14', delToken: 'del-btn-style' }; const customElements = { check: <span className="check">✓</span>, dropdownArrow: ' ▾' }; class App extends Component { constructor(props) { super(props); this.state = { dropdownSections: [] }; } renderToken(token) { return TokenTypes.getTokenType(token.type).renderToken(token); } onChange({ tokens, searchText }) { const requestId = Date.now(); this.requestId = requestId; TokenTypes.getTokenSuggestions(searchText).then(dropdownSections => { if (this.requestId === requestId) { this.setState({ dropdownSections }); } }); } render() { return ( <FacetedTokenInput customElements={customElements} componentClasses={componentClasses} renderToken={this.renderToken} dropdownSections={this.state.dropdownSections} placeholder="Search…" defaultTokens={[]} onChange={event => this.onChange(event)} /> ); } } class Results extends Component { render() { return ( <div className="list-group"> {RESULTS.map((result, index) => <a key={'result' + index} href="#" className="list-group-item"> <p className="list-group-item-text pull-right"> {result.createDate} </p> <h4 className="list-group-item-heading"> {result.description || '…'}{' '} <small>({result.status})</small> </h4> <p className="list-group-item-text">{result.product}</p> </a> )} </div> ); } } storiesOf('Token Input', module).add('Example', () => <div> <div className="bar"> <div className="opensquare" /> <div className="grow"> <App /> </div> </div> <hr /> <Results /> </div> );
www/imports/mapPage/shortlist/attrAdd.js
terraswat/hexagram
// addAttr.js // This allows the user to add new dynamic attributes to the current map. import React, { Component } from 'react'; import { render } from 'react-dom'; import DialogHex from '/imports/common/DialogHex'; import Layer from '/imports/mapPage/longlist/Layer'; import { ReadFile } from '/imports/component/ReadFile' import rx from '/imports/common/rx'; import userMsg from '/imports/common/userMsg'; import '/imports/mapPage/shortlist/attrAdd.html'; var dialogHex = null; function destroy() { dialogHex.hide(); dialogHex = undefined; } addAsLayers = function (data) { // Load the data into the shortlist. // Find unique names for the attributes. var attrNames = _.map(data[0].slice(1), function (origName) { return Layer.make_unique_name(origName); }), dynLayers = {}; // Create the basic layer entry. _.each(attrNames, function (name) { dynLayers[name] = { data: {}, dynamic: true }; }); // Load the values in each row. _.each(data.slice(1), function (row) { var nodeId = row[0]; _.each(row.slice(1), function (val, i) { dynLayers[attrNames[i]].data[nodeId] = val; }); }); // Add all the layers to our layers global and the shortlist. Layer.with_many(attrNames, () => { rx.set('shortlist.addDynamicByAddAttr', { attrs: attrNames } ) }, dynLayers); rx.set('attrAdd:adding.done'); // Destroy this dialogHex. destroy(); }; function handleReadStart() { rx.set('attrAdd:adding.now'); } function handleReadError(msg) { rx.set('attrAdd:adding.done'); userMsg.error(msg); } export function create() { // Create the dialog. if (!dialogHex) { // Retrieve the html template. Blaze.render(Template.attrAddTemplate, $('.content')[0]); // Attach the html to the page content. let $dialog = $('#attrAddDialog'); $('.content').append($dialog); // Attach the file reader render( <ReadFile parseTsv = {true} onSuccess = {addAsLayers} onStart = {handleReadStart} onError = {handleReadError} />, $dialog.find('.fileAnchor')[0]); // Create a dialog and show it. dialogHex = DialogHex.create({ $el: $dialog, opts: { title: 'Add Color Attributes' }, helpAnchor: '/help/addAttr.html', }); } dialogHex.show(); }
client/src/components/shared/StateDropdown.js
wolnewitz/raptor-ads
import React from 'react'; import { Dropdown } from 'semantic-ui-react'; import stateOptions from '../helpers/stateOptions'; const StateDropdown = ({ onChange }) => <div className="field"> <label htmlFor="state">State</label> <Dropdown placeholder="State" options={stateOptions} search selection fluid onChange={(e, data) => onChange(e, data)} /> </div>; export default StateDropdown;
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
Jeremy-Meng/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; import ActorClient from 'utils/ActorClient'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import TypingActionCreators from 'actions/TypingActionCreators'; import DraftActionCreators from 'actions/DraftActionCreators'; import DraftStore from 'stores/DraftStore'; import AvatarItem from 'components/common/AvatarItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { text: DraftStore.getDraft(), profile: ActorClient.getUser(ActorClient.getUid()) }; }; @ReactMixin.decorate(PureRenderMixin) class ComposeSection extends React.Component { static propTypes = { peer: React.PropTypes.object.isRequired }; static childContextTypes = { muiTheme: React.PropTypes.object }; constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); DraftStore.addLoadDraftListener(this.onDraftLoad); } componentWillUnmount() { DraftStore.removeLoadDraftListener(this.onDraftLoad); } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } onDraftLoad = () => { this.setState(getStateFromStores()); }; onChange = event => { TypingActionCreators.onTyping(this.props.peer); this.setState({text: event.target.value}); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this.sendTextMessage(); } else if (event.keyCode === 50 && event.shiftKey) { console.warn('Mention should show now.'); } }; onKeyUp = () => { DraftActionCreators.saveDraft(this.state.text); }; sendTextMessage = () => { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } this.setState({text: ''}); DraftActionCreators.saveDraft('', true); }; onSendFileClick = () => { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }; onSendPhotoClick = () => { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }; onFileInputChange = () => { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }; onPhotoInputChange = () => { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }; onPaste = event => { let preventDefault = false; _.forEach(event.clipboardData.items, (item) => { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }; render() { const text = this.state.text; const profile = this.state.profile; return ( <section className="compose" onPaste={this.onPaste}> <AvatarItem image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this.onChange} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp} value={text}> </textarea> <footer className="compose__footer row"> <button className="button" onClick={this.onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this.onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this.onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this.onPhotoInputChange} type="file"/> </div> </section> ); } } export default ComposeSection;
actor-apps/app-web/src/app/components/common/State.react.js
hmoraes/actor-platform
import React from 'react'; import { MessageContentTypes } from 'constants/ActorAppConstants'; class State extends React.Component { static propTypes = { message: React.PropTypes.object.isRequired }; render() { const { message } = this.props; if (message.content.content === MessageContentTypes.SERVICE) { return null; } else { let icon = null; switch(message.state) { case 'pending': icon = <i className="status status--penging material-icons">access_time</i>; break; case 'sent': icon = <i className="status status--sent material-icons">done</i>; break; case 'received': icon = <i className="status status--received material-icons">done_all</i>; break; case 'read': icon = <i className="status status--read material-icons">done_all</i>; break; case 'error': icon = <i className="status status--error material-icons">report_problem</i>; break; default: } return ( <div className="message__status">{icon}</div> ); } } } export default State;
src/components/common/mediaPicker/results/FeaturedFavoriteGeoSearchResultsContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import withAsyncData from '../../hocs/AsyncDataContainer'; import { selectMediaPickerQueryArgs, fetchMediaPickerFeaturedCollections, fetchFavoriteCollections, fetchFavoriteSources, fetchMediaPickerCountryCollections } from '../../../../actions/systemActions'; import TabSearchResultsContainer from './TabSearchResultsContainer'; import { TAG_SET_ABYZ_GEO_COLLECTIONS, TAG_SET_MC_ID } from '../../../../lib/tagUtil'; const localMessages = { title: { id: 'system.mediaPicker.collections.title', defaultMessage: 'Collections matching "{name}"' }, hintText: { id: 'system.mediaPicker.collections.hint', defaultMessage: 'Search collections by name' }, noResults: { id: 'system.mediaPicker.collections.noResults', defaultMessage: 'No results. Try searching for issues like online news, health, blogs, conservative to see if we have collections made up of those types of sources.' }, }; class FeaturedFavoriteGeoSearchResultsContainer extends React.Component { UNSAFE_componentWillMount() { this.correlateSelection(this.props); } UNSAFE_componentWillReceiveProps(nextProps) { // PICK_FEATURED if (nextProps.selectedMediaQueryType !== this.props.selectedMediaQueryType) { this.updateMediaQuery({ type: nextProps.selectedMediaQueryType }); } if (nextProps.selectedMedia !== this.props.selectedMedia // if the results have changed from a keyword entry, we need to update the UI || (nextProps.featured && nextProps.featured.lastFetchSuccess !== this.props.featured.lastFetchSuccess) || (nextProps.favoritedCollections && nextProps.favoritedCollections.lastFetchSuccess !== this.props.favoritedCollections.lastFetchSuccess) || (nextProps.favoritedSources && nextProps.favoritedSources.lastFetchSuccess !== this.props.favoritedSources.lastFetchSuccess)) { this.correlateSelection(nextProps); } } correlateSelection(whichProps) { let whichList = []; if ((whichProps.favoritedCollections.list && whichProps.favoritedCollections.list.length > 0) || (whichProps.favoritedSources.list && whichProps.favoritedSources.list.length > 0)) { whichList = whichProps.favoritedCollections.list; whichList = whichList.concat(whichProps.favoritedSources.list); } whichList = whichList.concat(whichProps.featured.list); // if selected media has changed, update current results if (whichProps.selectedMedia && whichProps.selectedMedia.length > 0 // we can't be sure we have received results yet && whichList && whichList.length > 0) { // sync up selectedMedia and push to result sets. whichList.map((m) => { const mediaIndex = whichProps.selectedMedia.findIndex(q => q.id === m.id); if (mediaIndex < 0) { this.props.handleMediaConcurrency(m, false); } else if (mediaIndex >= 0) { this.props.handleMediaConcurrency(m, true); } return m; }); } return 0; } updateMediaQuery(values) { const { updateMediaQuerySelection, selectedMediaQueryType } = this.props; const updatedQueryObj = { ...values, type: selectedMediaQueryType }; updateMediaQuerySelection(updatedQueryObj); } render() { const { selectedMediaQueryType, featured, favoritedCollections, favoritedSources, onToggleSelected, fetchStatus } = this.props; const queryResults = { featured: featured.list, favoritedCollections: favoritedCollections.list, favoritedSources: favoritedSources.list, geographic: favoritedSources.list, }; return ( <div> <TabSearchResultsContainer fetchStatus={fetchStatus} onToggleSelected={onToggleSelected} selectedMediaQueryType={selectedMediaQueryType} queryResults={queryResults} initValues={{ storedKeyword: { mediaKeyword: '' } }} onSearch={val => this.updateMediaQuery(val)} hintTextMsg={localMessages.hintText} handleMediaConcurrency={this.props.handleMediaConcurrency} /> </div> ); } } FeaturedFavoriteGeoSearchResultsContainer.propTypes = { // form compositional chain intl: PropTypes.object.isRequired, // from parent onToggleSelected: PropTypes.func.isRequired, handleMediaConcurrency: PropTypes.func.isRequired, whichTagSet: PropTypes.array, // from dispatch updateMediaQuerySelection: PropTypes.func.isRequired, // from state selectedMedia: PropTypes.array, selectedMediaQueryType: PropTypes.number, featured: PropTypes.object, favoritedCollections: PropTypes.object, favoritedSources: PropTypes.object, fetchStatus: PropTypes.array.isRequired, displayResults: PropTypes.bool, }; const mapStateToProps = state => ({ fetchStatus: [ state.system.mediaPicker.favoritedCollections.fetchStatus, state.system.mediaPicker.favoritedSources.fetchStatus, state.system.mediaPicker.featured.fetchStatus, ], selectedMediaQueryType: state.system.mediaPicker.selectMediaQuery ? state.system.mediaPicker.selectMediaQuery.args.type : 0, selectedMedia: state.system.mediaPicker.selectMedia.list, featured: state.system.mediaPicker.featured ? state.system.mediaPicker.featured : null, favoritedCollections: state.system.mediaPicker.favoritedCollections ? state.system.mediaPicker.favoritedCollections : null, favoritedSources: state.system.mediaPicker.favoritedSources ? state.system.mediaPicker.favoritedSources : null, collectionResults: state.system.mediaPicker.countryCollectionQueryResults, }); const mapDispatchToProps = dispatch => ({ updateMediaQuerySelection: (values) => { if (values) { dispatch(selectMediaPickerQueryArgs(values)); dispatch(fetchMediaPickerFeaturedCollections(TAG_SET_MC_ID)); dispatch(fetchFavoriteCollections()); dispatch(fetchFavoriteSources()); dispatch(fetchMediaPickerCountryCollections()); } }, }); const fetchAsyncData = (dispatch) => { dispatch(selectMediaPickerQueryArgs({ type: 0 })); dispatch(fetchMediaPickerFeaturedCollections(TAG_SET_MC_ID)); dispatch(fetchFavoriteCollections()); dispatch(fetchFavoriteSources()); dispatch(fetchMediaPickerCountryCollections({ media_keyword: '', which_set: TAG_SET_ABYZ_GEO_COLLECTIONS })); }; export default injectIntl( connect(mapStateToProps, mapDispatchToProps)( withAsyncData(fetchAsyncData)( FeaturedFavoriteGeoSearchResultsContainer ) ) );
examples/tree-view/containers/Node.js
tappleby/redux
import React from 'react' import { Component } from 'react' import { connect } from 'react-redux' import * as actions from '../actions' export class Node extends Component { constructor(props) { super(props) this.handleIncrementClick = this.handleIncrementClick.bind(this) this.handleRemoveClick = this.handleRemoveClick.bind(this) this.handleAddChildClick = this.handleAddChildClick.bind(this) this.renderChild = this.renderChild.bind(this) } handleIncrementClick() { const { increment, id } = this.props increment(id) } handleAddChildClick(e) { e.preventDefault() const { addChild, createNode, id } = this.props const childId = createNode().nodeId addChild(id, childId) } handleRemoveClick(e) { e.preventDefault() const { removeChild, deleteNode, parentId, id } = this.props removeChild(parentId, id) deleteNode(id) } renderChild(childId) { const { id } = this.props return ( <li key={childId}> <ConnectedNode id={childId} parentId={id} /> </li> ) } render() { const { counter, parentId, childIds } = this.props return ( <div> Counter: {counter} {' '} <button onClick={this.handleIncrementClick}> + </button> {' '} {typeof parentId !== 'undefined' ? <a href="#" onClick={this.handleRemoveClick} style={{ color: 'lightgray', textDecoration: 'none' }}> × </a> : null } <ul> {childIds.map(this.renderChild)} <li key="add"> <a href="#" onClick={this.handleAddChildClick}> Add child </a> </li> </ul> </div> ) } } function mapStateToProps(state, ownProps) { return state[ownProps.id] } const ConnectedNode = connect(mapStateToProps, actions)(Node) export default ConnectedNode
docs/src/pages/components/tree-view/ControlledTreeView.js
lgollut/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import TreeView from '@material-ui/lab/TreeView'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import TreeItem from '@material-ui/lab/TreeItem'; const useStyles = makeStyles({ root: { height: 216, flexGrow: 1, maxWidth: 400, }, }); export default function ControlledTreeView() { const classes = useStyles(); const [expanded, setExpanded] = React.useState([]); const [selected, setSelected] = React.useState([]); const handleToggle = (event, nodeIds) => { setExpanded(nodeIds); }; const handleSelect = (event, nodeIds) => { setSelected(nodeIds); }; return ( <TreeView className={classes.root} defaultCollapseIcon={<ExpandMoreIcon />} defaultExpandIcon={<ChevronRightIcon />} expanded={expanded} selected={selected} onNodeToggle={handleToggle} onNodeSelect={handleSelect} > <TreeItem nodeId="1" label="Applications"> <TreeItem nodeId="2" label="Calendar" /> <TreeItem nodeId="3" label="Chrome" /> <TreeItem nodeId="4" label="Webstorm" /> </TreeItem> <TreeItem nodeId="5" label="Documents"> <TreeItem nodeId="6" label="Material-UI"> <TreeItem nodeId="7" label="src"> <TreeItem nodeId="8" label="index.js" /> <TreeItem nodeId="9" label="tree-view.js" /> </TreeItem> </TreeItem> </TreeItem> </TreeView> ); }
src/components/SliderTransparency.js
ekatzenstein/three.js-live
import React from 'react'; import Slider from 'material-ui/Slider'; /** * The `defaultValue` property sets the initial position of the slider. * The slider appearance changes when not at the starting position. */ const SliderTransparency = (props) => ( <Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}} data-tip={`Opacity`} data-offset="{'top': -30}" /> ); export default SliderTransparency;
src/ButtonGroup.js
omerts/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const ButtonGroup = React.createClass({ mixins: [BootstrapMixin], propTypes: { vertical: React.PropTypes.bool, justified: React.PropTypes.bool, /** * Display block buttons, only useful when used with the "vertical" prop. * @type {bool} */ block: CustomPropTypes.all([ React.PropTypes.bool, function(props, propName, componentName) { if (props.block && !props.vertical) { return new Error('The block property requires the vertical property to be set to have any effect'); } } ]) }, getDefaultProps() { return { bsClass: 'button-group' }; }, render() { let classes = this.getBsClassSet(); classes['btn-group'] = !this.props.vertical; classes['btn-group-vertical'] = this.props.vertical; classes['btn-group-justified'] = this.props.justified; classes['btn-block'] = this.props.block; return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default ButtonGroup;
src/svg-icons/editor/format-bold.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatBold = (props) => ( <SvgIcon {...props}> <path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/> </SvgIcon> ); EditorFormatBold = pure(EditorFormatBold); EditorFormatBold.displayName = 'EditorFormatBold'; EditorFormatBold.muiName = 'SvgIcon'; export default EditorFormatBold;
docs/app/Examples/modules/Checkbox/States/CheckboxExampleChecked.js
aabustamante/Semantic-UI-React
import React from 'react' import { Checkbox } from 'semantic-ui-react' const CheckboxExampleChecked = () => ( <Checkbox label='This checkbox comes pre-checked' defaultChecked /> ) export default CheckboxExampleChecked
src/svg-icons/device/battery-std.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryStd = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryStd = pure(DeviceBatteryStd); DeviceBatteryStd.displayName = 'DeviceBatteryStd'; DeviceBatteryStd.muiName = 'SvgIcon'; export default DeviceBatteryStd;
website/irulez/src/components/SideBar.js
deklungel/iRulez
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import CssBaseline from '@material-ui/core/CssBaseline'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import ExpandLess from '@material-ui/icons/ExpandLess'; import ExpandMore from '@material-ui/icons/ExpandMore'; import Collapse from '@material-ui/core/Collapse'; import { NavLink } from 'react-router-dom'; import { withRouter } from 'react-router-dom'; import PeopleIcon from '@material-ui/icons/People'; import PersonIcon from '@material-ui/icons/Person'; import WallIcon from 'mdi-react/WallIcon'; import LogoutIcon from 'mdi-react/LogoutIcon'; import ChipIcon from 'mdi-react/ChipIcon'; import CogsIcon from 'mdi-react/CogsIcon'; import GaugeIcon from 'mdi-react/GaugeIcon'; import DnsOutlineIcon from 'mdi-react/DnsOutlineIcon'; import LightbulbOnOutlineIcon from 'mdi-react/LightbulbOnOutlineIcon'; import ArrowExpandLeftIcon from 'mdi-react/ArrowExpandLeftIcon'; import ArrowExpandRightIcon from 'mdi-react/ArrowExpandRightIcon'; import FileTreeIcon from 'mdi-react/FileTreeIcon'; const drawerWidth = 240; const styles = theme => ({ root: { display: 'flex' }, appBar: { transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen }) }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen }) }, menuButton: { marginLeft: 12, marginRight: 20 }, hide: { display: 'none' }, drawer: { width: drawerWidth, flexShrink: 0 }, drawerPaper: { width: drawerWidth }, drawerHeader: { display: 'flex', alignItems: 'center', padding: '0 8px', ...theme.mixins.toolbar, justifyContent: 'flex-end' }, nested: { paddingLeft: theme.spacing.unit * 4 }, active: { backgroundColor: 'rgba(0, 0, 0, 0.14)' } }); function ListItemLink(props) { const { primary, to, icon, className, classes } = props; return ( <li> <ListItem button className={className} activeClassName={classes.active} component={NavLink} exact to={to}> <ListItemIcon>{icon}</ListItemIcon> <ListItemText inset primary={primary} /> </ListItem> </li> ); } ListItemLink.propTypes = { primary: PropTypes.node.isRequired, to: PropTypes.string.isRequired }; class SideBar extends React.Component { constructor(props) { super(props); this.handleLogout = this.handleLogout.bind(this); } state = { //open: true, subopen: false }; handleClick = menu => { this.props.ToggleCollapse(menu); }; handleDrawerOpen = () => { // this.setState({ open: true }); this.props.sidebarToggle(true); }; handleDrawerClose = () => { // this.setState({ open: false }); this.props.sidebarToggle(false); }; handleLogout() { this.props.Auth.logout(); this.props.history.replace('/login'); // history.push('/login') } render() { const { classes, theme } = this.props; const { open } = this.props; return ( <div className={classes.root}> <CssBaseline /> <AppBar position='fixed' className={classNames(classes.appBar, { [classes.appBarShift]: open })} > <Toolbar disableGutters={!open}> <IconButton color='inherit' aria-label='Open drawer' onClick={this.handleDrawerOpen} className={classNames(classes.menuButton, open && classes.hide)} > <MenuIcon /> </IconButton> <Typography variant='h6' color='inherit' noWrap> iRulez Administration </Typography> </Toolbar> </AppBar> <Drawer className={classes.drawer} variant='persistent' anchor='left' open={open} classes={{ paper: classes.drawerPaper }} > <div className={classes.drawerHeader}> <IconButton onClick={this.handleDrawerClose}> {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> <Divider /> <List component='nav'> <ListItemLink to='/administrator' classes={classes} button primary='Dashboard' icon={<GaugeIcon />} /> <ListItem button onClick={() => { this.handleClick('actions'); }} > <ListItemIcon> <CogsIcon /> </ListItemIcon> <ListItemText inset primary='Actions' /> {this.state.actions ? <ExpandLess /> : <ExpandMore />} </ListItem> <Collapse in={this.props.MenuOpen === 'actions'} timeout='auto' unmountOnExit> <List component='div' disablePadding> <ListItemLink to='/administrator/actions/relais' className={classes.nested} classes={classes} primary='Relais Actions' icon={<CogsIcon />} /> <ListItemLink to='/administrator/actions/dimmer' className={classes.nested} classes={classes} primary='Dimmer Actions' icon={<CogsIcon />} /> </List> </Collapse> <ListItemLink to='/administrator/menus' classes={classes} button primary='Menus' icon={<FileTreeIcon />} /> <ListItemLink to='/administrator/devices' classes={classes} button primary='Devices' icon={<DnsOutlineIcon />} /> <ListItemLink to='/administrator/inputs' classes={classes} button primary='Input' icon={<ArrowExpandRightIcon />} /> <ListItemLink to='/administrator/outputs' classes={classes} button primary='Output' icon={<ArrowExpandLeftIcon />} /> <ListItemLink to='/administrator/processes' classes={classes} button primary='Processes' icon={<ChipIcon />} /> <ListItem button> <ListItemIcon> <LightbulbOnOutlineIcon /> </ListItemIcon> <ListItemText inset primary='vButtons' /> </ListItem> <ListItem button onClick={() => { this.handleClick('user'); }} > <ListItemIcon> <PeopleIcon /> </ListItemIcon> <ListItemText inset primary='Users' /> {this.state.user ? <ExpandLess /> : <ExpandMore />} </ListItem> <Collapse in={this.props.MenuOpen === 'user'} timeout='auto' unmountOnExit> <List component='div' disablePadding> <ListItemLink to='/administrator/user/users' className={classes.nested} classes={classes} primary='Add/edit' icon={<PersonIcon />} /> <ListItemLink to='/administrator/user/groups' className={classes.nested} classes={classes} primary='Groups' icon={<PersonIcon />} /> </List> </Collapse> <Divider /> <ListItem button onClick={this.handleLogout}> <ListItemIcon> <LogoutIcon /> </ListItemIcon> <ListItemText primary='Logout' /> </ListItem> </List> </Drawer> </div> ); } } SideBar.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired }; export default withStyles(styles, { withTheme: true })(withRouter(SideBar));
src-admin/src/Components/CustomModal.js
ioBroker/ioBroker.admin
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import { Dialog } from '@material-ui/core'; import PropTypes from 'prop-types'; const useStyles = makeStyles((theme) => ({ modalContentWrapper: { margin: '20px 0', padding: '0 35px', // background: '#f6f6f6', overflowX: 'hidden', minWidth: '320px' }, modalButtonBlock: { display: 'flex', justifyContent: 'flex-end', marginTop: '20px', flexFlow: 'wrap', borderTop: '1px solid silver' }, modalButtonBlockTwo: { justifyContent: 'space-around', flexFlow: 'wrap-reverse', '& button': { margin: '5px' } }, modalWrapper: { position: 'relative', '[class*="MuiPaper-root MuiDialog-paper MuiDialog-paperScrollPaper MuiDialog-paperWidthXl MuiPaper-elevation24 MuiPaper-rounded"]': { background: '#f6f6f6' } }, close: { position: 'absolute', right: '8px', top: '6px', width: '32px', height: '32px', opacity: '0.9', cursor: 'pointer', transition: 'all 0.6s ease', '&:hover': { transform: 'rotate(90deg)' }, '&:before': { position: 'absolute', left: '15px', content: '""', height: '33px', width: '4px', backgroundColor: '#ff4f4f', transform: 'rotate(45deg)' }, '&:after': { position: 'absolute', left: '15px', content: '""', height: '33px', width: '4px', backgroundColor: '#ff4f4f', transform: 'rotate(-45deg)' }, }, '@media screen and (max-width: 460px)': { modalContentWrapper: { minWidth: 'auto' } } })); const CustomModal = ({ open, close, children, titleOk, titleCancel, buttonClick }) => { const classes = useStyles(); return <Dialog open={open} maxWidth="md" disableEscapeKeyDown={true} onClose={close} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" className={classes.modalWrapper || ''} > <div className={classes.modalContentWrapper}> <div className={classes.close} onClick={close} /> {children} <div className={`${classes.modalButtonBlock} ${titleOk ? classes.modalButtonBlockTwo : ''}`}> {titleOk && <Button variant="contained" onClick={buttonClick} color="primary" autoFocus={}>{titleOk}</Button>} {titleCancel && <Button variant="contained" onClick={close}>{titleCancel}</Button>} </div> </div> </Dialog>; } CustomModal.defaultProps = { open: false, buttonClick: () => { }, close: () => { } }; CustomModal.propTypes = { open: PropTypes.bool, close: PropTypes.func, children: PropTypes.any, titleOk: PropTypes.string, titleCancel: PropTypes.string, buttonClick: PropTypes.func }; export default CustomModal;
examples/real-world/containers/Root.js
idolize/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
KevinKhieu/PeaceDashboard
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/components/PrevButton.js
CodeDraken/ES-Library
import React from 'react'; import {Link} from 'react-router-dom'; const PrevButton = ({url}) => { let prevPage = ''; if (url) { const i = (url).lastIndexOf('/'); if (i !== -1) { // end of the url const thisPage = (url).substr(i, 0) + url.substr(i); // take out the last /x part prevPage = url.replace(thisPage, '') || ''; } } const prevButton = url ? <Link to={prevPage} className="waves-effect waves-teal btn-flat"> <i className="fa fa-arrow-left" aria-hidden="true"></i> previous </Link> : ''; return ( <div> {prevButton} </div> ); }; export default PrevButton;
public/js/cat_source/es6/components/common/InputField.js
Ostico/MateCat
import React from 'react' import PropTypes from 'prop-types' const styleInput = { fontFamily: 'calibri, Arial, Helvetica, sans-serif', fontSize: '16px', padding: '10px 20px', borderRadius: '40px', outlineColor: '#e5e9f1', border: 'unset', boxShadow: '0px 0px 0px 1px rgba(34, 36, 38, 0.25) inset', display: 'flex', maxWidth: '150px', } const styleContainer = { position: 'relative', marginRight: '5px', } const styleIcon = { visibility: 'visible', right: '7px', cursor: 'pointer', } export default class InputField extends React.Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) this.resetInput = this.resetInput.bind(this) this.state = { value: this.props.value ? this.props.value : '', } this.debouncedOnChange = _.debounce(() => { this.props.onFieldChanged(this.state.value) }, 500) } handleChange(event) { this.setState({value: event.target.value}) this.debouncedOnChange() } resetInput() { this.setState({value: ''}) this.props.onFieldChanged('') } componentDidMount() { if (this.props.text) { var event = new Event('input', {bubbles: true}) this.input.dispatchEvent(event) } } render() { var type = 'text' if (this.props.type) { type = this.props.type } return ( <div className={'qr-filter-idSegment'} style={styleContainer}> <input style={styleInput} type={type} placeholder={this.props.placeholder} value={this.state.value} name={this.props.name} onChange={this.handleChange} className={this.props.classes} tabIndex={this.props.tabindex} onKeyPress={this.props.onKeyPress} ref={(input) => (this.input = input)} /> {this.props.showCancel && this.state.value.length > 0 ? ( <div data-testid="reset-button" className="ui cancel label" style={styleIcon} onClick={this.resetInput} > <i className="icon-cancel3" /> </div> ) : null} </div> ) } } InputField.propTypes = { onFieldChanged: PropTypes.func.isRequired, }
src/components/Page2.js
theJoeBiz/react-boilerplate
import React, { Component } from 'react'; class Page2 extends Component { render() { return ( <div>Page 2</div> ); } } export default Page2;
8-React-Basic-Crud/src/app/index_.js
ekaaditiac/React-Basic-API
import React from 'react'; import ReactDOM from 'react-dom'; import Request from 'superagent'; import _ from 'lodash'; const data = [ { author: "MadDog", text: "Papah bangga sama kamu nak", src:"https://2.bp.blogspot.com/-cD3bhrzhTSg/VKkI3PKXOoI/AAAAAAAAAes/YCsThXgLUXA/s400/gereget%2B(mad%2Bdog).jpg" }, { author: "MadDog Part II", text: "Maen Volly pakai duren", src:"https://cdns.klimg.com/newshub.id/news/2016/05/16/60450/271750-gregetnya-mad-dog.jpg" }, { author: "MadDog Part III", text: "asap kenalpot", src:"https://s-media-cache-ak0.pinimg.com/564x/1d/a7/fb/1da7fb629775ef74bd981ffb0fc734d4.jpg" } ] class App extends React.Component{ constructor(){ super(); this.state = {}; } componentDidMount(){ this.setState({ datas: data }); } render(){ var datas = _.map(this.state.datas,(data,i)=>{ return( <li key={i}> <h5>{data.author}</h5> <p>{data.text}</p> <img width="350" src={data.src} alt={data.text} /> </li> ) }) return( <div> <ul> {datas} </ul> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );
docs/src/shared/components/ReactMD/autocompletes/index.js
lwhitlock/grow-tracker
import React from 'react'; import MenuAutocomplete from './MenuAutocomplete'; import MenuAutocompleteRaw from '!!raw!./MenuAutocomplete'; import InlineAutocomplete from './InlineAutocomplete'; import InlineAutocompleteRaw from '!!raw!./InlineAutocomplete'; import AjaxAutocomplete from './AjaxAutocomplete'; import AjaxAutocompleteRaw from '!!raw!./AjaxAutocomplete'; import InToolbarExample from './InToolbarExample'; import InToolbarExampleRaw from '!!raw!./InToolbarExample'; import SearchRaw from '!!raw!components/Search/Search'; import SearchSCSSRaw from '!!raw!components/Search/_search.scss'; export default [{ title: 'Menu Completion View', description: ` This example shows how you can use the two built in filters or a 3rd party library to do text matching. When the user starts typing, the \`Autocomplete\` will search the list of \`data\` for any text matching the current value. For this example, all the filtered data and results will appear in a drop down menu. `, code: MenuAutocompleteRaw, children: <MenuAutocomplete />, }, { title: 'Inline Completion View', description: ` This example shows how a completion can be done inline instead. By default, the autocomplete will find the first match and display it. It can be autocompleted by either: - pressing the tab key on desktops - tapping the selection text on touch devices The default \`findInlineSuggestion\` function just does a simple ignore case matching. See the PropTypes tab for more information. `, code: InlineAutocompleteRaw, children: <InlineAutocomplete />, }, { title: 'Ajax Autocomplete', description: ` A lot of the time, you won't actually have access to all of the autocomplete matches because you will be using some amazing backend indexer and apis to populate while the user types. Since the list of \`data\` will always be updating and the filtering is done by a server, set the \`filter\` prop to \`null\` to prevent any unneeded work on the client side. It is also normally helpful to set the \`type\` to \`search\` instead of the default \`text\`. The example below will use the [Spotify API](https://developer.spotify.com/web-api/endpoint-reference/) to search for an artist, and then display their albums once it is selected. `, code: AjaxAutocompleteRaw, children: <AjaxAutocomplete />, }, { title: 'Lazy Loading Ajax', description: ` Since the \`Autocomplete\` also accepts valid React elements in the list items that won't be searched, it is possible to create a lazy loading list of suggestions in the autocomplete. This is very beneficial when your api paginates the search results. This is actually how the main search has been implemented for this site. The site's search uses the [react-waypoint](https://github.com/brigade/react-waypoint) component to fetch the next 10 items in the search results when the user scrolls to the end of the list. This continues until there are no results remaining. You can view the source code for the search by clicking the source code button on this card. `, code: ` /* Search.jsx */ ${SearchRaw} \`\`\` \`\`\`scss ${SearchSCSSRaw} `, children: null, }, { title: 'In Toolbar', description: ` When an autocomplete appears in a toolbar, it will automatically update the list to appear below the toolbar and fixed to the entire width of the screen while tablets and desktops will be absolutely positioned and have a width equal to the text autocomplete's with. If you want the text field to gain the font size of the toolbar's normal font size, you will need to add \`inputClassName="md-text-field--toolbar"\` to the autocomplete. If you want the autocomplete to align with the default title keyline, you will need to add the \`className="md-title--toolbar"\` to the autocomplete. `, code: InToolbarExampleRaw, children: <InToolbarExample />, }];
NewCardModal.js
jasonlarue/react-native-flashcards
import React from 'react'; import { StyleSheet, Text, Modal, View, TextInput, TouchableHighlight } from 'react-native'; export default class NewCardModal extends React.Component { state = { newTermInput: '', newDefinitionInput: '' } render() { return ( <Modal animationType={'fade'} transparent={false} visible={this.props.modalVisible} > <View style={styles.newCardModal}> <TouchableHighlight onPress={this.props.toggleModal} underlayColor='transparent' style={styles.closeButton} > <Text style={styles.closeButtonText}>✕</Text> </TouchableHighlight> <TextInput placeholder='New Term' style={styles.newTermInput} value={this.state.newTermInput} onChangeText={(text) => { this.setState({ newTermInput: text }); }} /> <TextInput placeholder='New Definition' style={styles.newDefinitionInput} value={this.state.newDefinitionInput} multiline={true} onChangeText={(text) => { this.setState({ newDefinitionInput: text }); }} /> <TouchableHighlight style={styles.addCardButton} underlayColor='#0A5E2D' onPress={() => { const {newTermInput, newDefinitionInput} = this.state; this.props.addCard(newTermInput, newDefinitionInput); // Reset inputs this.setState({ newTermInput: '', newDefinitionInput: '' }) }} > <Text style={styles.addCardButtonText}>Add Card</Text> </TouchableHighlight> </View> </Modal> ); } } const styles = StyleSheet.create({ newCardModal: { flex: 1, backgroundColor: '#2ecc71', justifyContent: 'center', alignContent: 'center' }, newTermInput: { backgroundColor: '#ffffff', borderColor: '#F2F2F2', borderWidth: 1, padding: 15, margin: 10, marginLeft: 20, marginRight: 20, fontSize: 18 }, newDefinitionInput: { backgroundColor: '#ffffff', borderColor: '#F2F2F2', borderWidth: 1, padding: 15, margin: 10, marginLeft: 20, marginRight: 20, fontSize: 18, height: 120 }, closeButton: { position: 'absolute', top: 30, right: 15, backgroundColor: 'transparent', justifyContent: 'center' }, closeButtonText: { textAlign: 'center', fontSize: 40, color: '#FFFFFF' }, addCardButton: { backgroundColor: '#128040', marginTop: 10, marginLeft: 20, marginRight: 20, padding: 20 }, addCardButtonText: { color: '#FFFFFF', fontSize: 18 } });
src/iron-components/index.stories.js
jonniespratley/px-components-react
import React from 'react'; import { storiesOf } from '@storybook/react'; //addons import { action } from '@storybook/addon-actions'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, text, array, object, boolean, number } from '@storybook/addon-knobs'; //component import IronCollapse from './iron-collapse'; //stories const stories = storiesOf('IronCollapse', module); stories .addDecorator(withKnobs) .add('simple info', withInfo({text: 'String or React Element with docs about my component'})(() => <IronCollapse>Click the "?" mark at top-right to view the info.</IronCollapse> ) ) .add('default', () => ( <IronCollapse onClick={action('clicked')}>This is collapsable content.</IronCollapse> )) module.exports = stories;
app/scripts/partials/PageHeader.react.js
darbio/auth0-roles-permissions-dashboard-sample
import React from 'react'; import BS from 'react-bootstrap'; export default class PageHeader extends React.Component { render() { return ( <div className="row page-header"> <div className="col-md-6"> <h2>{this.props.title}</h2> </div> <div className="col-md-6"> {this.props.children} </div> </div> ); } }
docs/app/Examples/elements/Segment/Variations/SegmentExampleInverted.js
mohammed88/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleInverted = () => ( <Segment inverted> Inverted content. </Segment> ) export default SegmentExampleInverted
react-dev/containers/posts_index.js
DeryLiu/DeryLiu.github.io
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { PostIndexItem } from '../components/post_index_item'; import { fetchPosts, fetchSiteInfo } from '../actions/index'; class PostsIndex extends Component { componentWillMount() { this.props.fetchPosts(); this.props.fetchSiteInfo(); } render() { return ( <div> <PostIndexItem posts={this.props.posts} siteInfo={this.props.siteInfo} /> </div> ); } } function mapStateToProps(state) { return { posts: state.posts.all, siteInfo: state.siteInfo.all }; } export default connect(mapStateToProps, { fetchPosts, fetchSiteInfo })(PostsIndex);
app/stem/components/StemProfile.js
Jawnkuin/electron-618-im
import React from 'react'; import { Button, Icon } from 'antd'; import PropTypes from 'prop-types'; import styles from './StemProfile.less'; import dummyimage from '../../utils/dummyimage'; const StemProfile = ({ userInfo }) => ( <div className={styles.ProfileContainer}> <div className={styles.ImgBox}> <img alt={userInfo.userNickName} src={dummyimage(userInfo.userNickName, null, 50)} /> </div> <div className={styles.DetailBox}> <div className={styles.NameBox}> {(userInfo && userInfo.userNickName) && userInfo.userNickName} <Button size="small" icon="check-circle" ghost /> </div> <div className={styles.SignBox}> 编辑个性签名 </div> <div className={styles.ToolBox}> <div className={styles.LeftBox}> <a href="http://www.fjqyw.com:7080/fjbidoa"><Icon type="home" /></a> </div> <div className={styles.RightBox}> <Button icon="message" ghost /> </div> </div> </div> </div> ); StemProfile.propTypes = { userInfo: PropTypes.shape({ userNickName: PropTypes.string }).isRequired }; export default StemProfile;
frontend/src/containers/Replay/Replay.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Helmet } from 'react-helmet'; import { asyncConnect } from 'redux-connect'; import { batchActions } from 'redux-batched-actions'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import { getCollectionLink, remoteBrowserMod, truncate } from 'helpers/utils'; import config from 'config'; import { getActivePage } from 'store/selectors'; import { isLoaded, load as loadColl } from 'store/modules/collection'; import { getArchives, setBookmarkId, setList, updateUrl, updateUrlAndTimestamp } from 'store/modules/controls'; import { resetStats } from 'store/modules/infoStats'; import { listLoaded, load as loadList } from 'store/modules/list'; import { load as loadBrowsers, isLoaded as isRBLoaded, setBrowser } from 'store/modules/remoteBrowsers'; import { toggle as toggleSidebar } from 'store/modules/sidebar'; import { AppContext } from 'store/contexts'; import EmbedFooter from 'components/EmbedFooter'; import HttpStatus from 'components/HttpStatus'; import RedirectWithStatus from 'components/RedirectWithStatus'; import Resizable from 'components/Resizable'; import { InspectorPanel, RemoteBrowser, Sidebar, SidebarListViewer, SidebarCollectionViewer, SidebarPageViewer } from 'containers'; import { IFrame, ReplayUI } from 'components/controls'; let Webview; if (__DESKTOP__) { Webview = require('components/desktop/Webview'); } class Replay extends Component { static contextType = AppContext; static propTypes = { activeBookmarkId: PropTypes.string, activeBrowser: PropTypes.string, appSettings: PropTypes.object, behavior: PropTypes.bool, auth: PropTypes.object, collection: PropTypes.object, dispatch: PropTypes.func, expanded: PropTypes.bool, list: PropTypes.object, loaded: PropTypes.bool, match: PropTypes.object, recording: PropTypes.string, sidebarResize: PropTypes.bool, timestamp: PropTypes.string, toggleSidebar: PropTypes.func, url: PropTypes.string }; constructor(props) { super(props); // TODO: unify replay and replay-coll this.mode = 'replay-coll'; this.state = { collectionNav: !props.match.params.listSlug }; } shouldComponentUpdate(nextProps) { // don't rerender for loading changes if (!nextProps.loaded) { return false; } return true; } componentDidUpdate(prevProps) { const { match: { params: { listSlug } } } = prevProps; if (listSlug !== this.props.match.params.listSlug && this.state.collectionNav) { this.setState({ collectionNav: false }); } } componentWillUnmount() { // clear info stats this.props.dispatch(resetStats()); } getAppPrefix = () => { const { activeBookmarkId, match: { params: { user, coll, listSlug } } } = this.props; return listSlug ? `${config.appHost}/${user}/${coll}/list/${listSlug}/b${activeBookmarkId}/` : `${config.appHost}/${user}/${coll}/`; } getContentPrefix = () => { const { activeBookmarkId, match: { params: { user, coll, listSlug } } } = this.props; return listSlug ? `${config.contentHost}/${user}/${coll}/list/${listSlug}/b${activeBookmarkId}/` : `${config.contentHost}/${user}/${coll}/`; } showCollectionNav = (bool = true) => { this.setState({ collectionNav: bool }); } render() { const { isEmbed, isMobile } = this.context; const { activeBookmarkId, activeBrowser, appSettings, auth, collection, dispatch, list, match: { params }, recording, timestamp, url } = this.props; const { coll, rec, user } = params; const canAdmin = auth.getIn(['user', 'username']) === user; // coll access if (collection.get('error')) { return ( <HttpStatus> {collection.getIn(['error', 'error_message'])} </HttpStatus> ); } else if (collection.get('loaded') && !collection.get('slug_matched') && coll !== collection.get('slug')) { return ( <RedirectWithStatus to={`${isEmbed ? `/${params.embed}` : ''}${getCollectionLink(collection)}/${remoteBrowserMod(activeBrowser, timestamp)}/${url}`} status={301} /> ); } // list access if (params.listSlug && (list.get('error') || (!list.get('slug_matched') && params.listSlug !== list.get('slug')))) { if (list.get('loaded') && !list.get('slug_matched')) { return ( <RedirectWithStatus to={`${isEmbed ? `/${params.embed}` : ''}${getCollectionLink(collection)}/list/${list.get('slug')}/b${activeBookmarkId}/${timestamp}/${url}`} status={301} /> ); } return ( <HttpStatus> { list.get('error') === 'no_such_list' && <span>Sorry, we couldn't find that list.</span> } </HttpStatus> ); } const tsMod = remoteBrowserMod(activeBrowser, timestamp); const { listSlug } = params; const bkId = params.bookmarkId; const shareUrl = listSlug ? `${config.appHost}${user}/${coll}/list/${listSlug}/b${bkId}/${tsMod}/${url}` : `${config.appHost}${user}/${coll}/${tsMod}/${url}`; if (!collection.get('loaded')) { return null; } const title = listSlug ? `Archived page from the “${list.get('title')}” List on ${config.product}` : `Archived page from the “${collection.get('title')}” Collection on ${config.product}`; const desc = listSlug ? <meta property="og:description" content={list.get('desc') ? truncate(list.get('desc'), 3, new RegExp(/([.!?])/)) : config.tagline} /> : <meta property="og:description" content={collection.get('desc') ? truncate(collection.get('desc'), 3, new RegExp(/([.!?])/)) : config.tagline} />; return ( <React.Fragment> <Helmet> <title>{title}</title> <meta property="og:url" content={shareUrl} /> <meta property="og:type" content="website" /> <meta property="og:title" content={title} /> {desc} </Helmet> { !isEmbed && <ReplayUI activeBrowser={activeBrowser} canAdmin={canAdmin} currMode={this.mode} canGoBackward={__DESKTOP__ ? appSettings.get('canGoBackward') : false} canGoForward={__DESKTOP__ ? appSettings.get('canGoForward') : false} params={params} timestamp={timestamp} sidebarExpanded={this.props.expanded} toggle={this.props.toggleSidebar} url={url} /> } <div className={classNames('iframe-container', { embed: isEmbed && params.embed !== '_embed_noborder' })}> { !isMobile && !isEmbed && <Sidebar defaultExpanded={Boolean(listSlug) || __DESKTOP__} storageKey={listSlug ? 'listReplaySidebar' : 'pageReplaySidebar'}> <Resizable axis="y" minHeight={200} storageKey="replayNavigator"> <Tabs defaultIndex={listSlug ? 0 : 1}> <TabList> <Tab>Lists</Tab> { (collection.get('public_index') || canAdmin) && <Tab>Browse All</Tab> } </TabList> <TabPanel> { this.state.collectionNav ? (<SidebarCollectionViewer activeList={listSlug} showNavigator={this.showCollectionNav} />) : <SidebarListViewer canAdmin={canAdmin} showNavigator={this.showCollectionNav} /> } </TabPanel> <TabPanel> <SidebarPageViewer showNavigator={this.showCollectionNav} /> </TabPanel> </Tabs> </Resizable> <InspectorPanel canAdmin={canAdmin} /> </Sidebar> } { __DESKTOP__ && <Webview currMode={this.mode} key="webview" host={appSettings.get('host')} params={params} dispatch={dispatch} timestamp={timestamp} canGoBackward={appSettings.get('canGoBackward')} canGoForward={appSettings.get('canGoForward')} partition={`persist:${user}-replay`} url={url} {...{ coll, user, rec }} /> } { isEmbed && params.embed !== '_embed_noborder' && <EmbedFooter timestamp={timestamp} /> } { !__DESKTOP__ && ( activeBrowser ? <RemoteBrowser currMode={this.mode} params={params} rb={activeBrowser} rec={recording} timestamp={timestamp} url={url} /> : <IFrame activeBookmarkId={activeBookmarkId} appPrefix={this.getAppPrefix} auth={this.props.auth} behavior={this.props.behavior} contentPrefix={this.getContentPrefix} currMode={this.mode} dispatch={dispatch} params={params} passEvents={this.props.sidebarResize} timestamp={timestamp} url={url} /> ) } </div> </React.Fragment> ); } } const initialData = [ { promise: ({ store: { dispatch, getState } }) => { const state = getState(); if (!isRBLoaded(state) && !__DESKTOP__) { return dispatch(loadBrowsers()); } return undefined; } }, { // set url, ts, list and bookmark id in store promise: ({ location: { hash, search }, match: { params: { bookmarkId, br, listSlug, ts, splat } }, store: { dispatch } }) => { const compositeUrl = `${splat}${search || ''}${hash || ''}`; return dispatch(batchActions([ ts ? updateUrlAndTimestamp(compositeUrl, ts) : updateUrl(compositeUrl), setBrowser(br || null), setList(listSlug || null), setBookmarkId(bookmarkId || null) ])); } }, { // check for list playback, load list promise: ({ match: { params: { user, coll, listSlug } }, store: { dispatch, getState } }) => { const state = getState(); if (listSlug && !listLoaded(listSlug, state)) { let host = ''; if (__DESKTOP__) { host = state.app.getIn(['appSettings', 'host']); } return dispatch(loadList(user, coll, listSlug, host)); } return undefined; } }, { promise: ({ match: { params }, store: { dispatch, getState } }) => { const state = getState(); const collection = state.app.get('collection'); const { user, coll } = params; if (!isLoaded(state) || collection.get('id') !== coll) { let host = ''; if (__DESKTOP__) { host = state.app.getIn(['appSettings', 'host']); } return dispatch(loadColl(user, coll, host)); } return undefined; } }, { promise: ({ store: { dispatch, getState } }) => { const { app } = getState(); // TODO: determine if we need to test for stale archives if (!app.getIn(['controls', 'archives']).size) { let host = ''; if (__DESKTOP__) { host = app.getIn(['appSettings', 'host']); } return dispatch(getArchives(host)); } return undefined; } } ]; const mapStateToProps = (outerState) => { const { reduxAsyncConnect: { loaded }, app } = outerState; const activePage = app.getIn(['collection', 'loaded']) ? getActivePage(outerState) : null; let appSettings = null; if (__DESKTOP__) { appSettings = app.get('appSettings'); } return { activeBrowser: app.getIn(['remoteBrowsers', 'activeBrowser']), activeBookmarkId: app.getIn(['controls', 'activeBookmarkId']), appSettings, behavior: app.getIn(['automation', 'behavior']), auth: app.get('auth'), collection: app.get('collection'), expanded: app.getIn(['sidebar', 'expanded']), list: app.get('list'), loaded, recording: activePage ? activePage.get('rec') : null, sidebarResize: app.getIn(['sidebar', 'resizing']), timestamp: app.getIn(['controls', 'timestamp']), url: app.getIn(['controls', 'url']) }; }; const mapDispatchToProps = (dispatch) => { return { toggleSidebar: b => dispatch(toggleSidebar(b)), dispatch }; }; export default asyncConnect( initialData, mapStateToProps, mapDispatchToProps )(Replay);
src/routes.js
rjbernaldo/lines
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import App from './components/App'; const routes = () => ( <Switch> <Route path="/" component={App} /> </Switch> ); export default routes;
webapp/js/components/app/NavigationBar.js
Stevenah/dhis2-datastore-application
import React, { Component } from 'react'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import Theme from 'utils/theme'; const imageStyle = { height: '20px', }; const toolBarStyle = { alignItems: 'center', backgroundColor: Theme.palette.primary1Color, color: Theme.palette.alternateTextColor, }; class NavigationBar extends Component { render() { return ( <Toolbar style={ toolBarStyle }> <img src="https://play.dhis2.org/test/api/staticContent/logo_banner" style={ imageStyle } alt="dhis2" /> <ToolbarTitle text="Datastore App" /> </Toolbar> ); } } export default NavigationBar;
src/containers/list-group.js
drifterz28/drizzle-maker
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { saveZones } from 'actions/save'; import DaysList from 'components/days-list'; import styles from 'scss/list-group.scss'; class ListGroup extends Component { static propTypes = { zone: PropTypes.number, duration: PropTypes.number, schedule: PropTypes.array, runTime: PropTypes.string } constructor(props) { super(props); const {zone, duration, schedule, runTime} = this.props; this.state = { zone, duration, schedule, runTime }; } parseName = (name) => { const day = name.split('-')[1]; return day; } handleCheckbox = (name, value) => { let {schedule} = this.state; const day = this.parseName(name); schedule[day] = value ? 1 : 0; this.setState({ schedule: schedule }); } handleChange = (e) => { const target = e.target; let name = target.name; let value = target.type === 'checkbox' ? target.checked : target.value; if(target.type === 'checkbox') { this.handleCheckbox(name, value); } else { this.setState({ [name]: value }); } } handleSave = (e) => { e.preventDefault(); const {saveZones, zones, zip} = this.props; saveZones(this.state, zones, zip); } render() { const {zone, duration, runTime, schedule} = this.state; const durationTime = duration > 0 ? duration : ''; return ( <ul className="list-group"> {schedule.map((day, i) => { return <DaysList zone={zone} status={day} key={i} index={i} handleChange={this.handleChange}/> })} <li className="list-group-item"> <div className="form-group"> <label htmlFor="runTime">Run Time</label> <input type="time" name="runTime" className="form-control" value={runTime} onChange={this.handleChange} id="runTime"/> </div> <div className="form-group pull-right"> <label htmlFor="duration">Duration <small>(in minutes)</small></label> <input type="number" className="form-control" name="duration" value={durationTime} id="duration" placeholder="In minutes" onChange={this.handleChange} /> <input type="hidden" name="zone" defaultValue={zone}/> </div> </li> <li className="list-group-item"> <button className="btn btn-block btn-primary" onClick={this.handleSave}>Save</button> </li> </ul> ); } }; export default connect( state => ({ zones: state.zones.zones, zip: state.zones.zip }), dispatch => bindActionCreators({ saveZones }, dispatch) )(ListGroup)
dist/lib/carbon-fields/assets/js/fields/components/textarea/index.js
ArtFever911/statrer-kit
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, withHandlers, setStatic } from 'recompose'; /** * The internal dependencies. */ import Field from 'fields/components/field'; import withStore from 'fields/decorators/with-store'; import withSetup from 'fields/decorators/with-setup'; import { TYPE_TEXTAREA, TYPE_HEADER_SCRIPTS, TYPE_FOOTER_SCRIPTS } from 'fields/constants'; /** * Render a multiline text input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Function} props.handleChange * @return {React.Element} */ export const TextareaField = ({ name, field, handleChange }) => { return <Field field={field}> <textarea id={field.id} name={name} value={field.value} rows={field.rows} disabled={!field.ui.is_visible} onChange={handleChange} {...field.attributes} /> </Field>; }; /** * Validate the props. * * @type {Object} */ TextareaField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ id: PropTypes.string, value: PropTypes.string, rows: PropTypes.number, attributes: PropTypes.object, }), handleChange: PropTypes.func, }; /** * The enhancer. * * @type {Function} */ export const enhance = compose( withStore(), withSetup(), /** * The handlers passed to the component. */ withHandlers({ handleChange: ({ field, setFieldValue }) => ({ target: { value } }) => setFieldValue(field.id, value), }) ); export default setStatic('type', [ TYPE_TEXTAREA, TYPE_HEADER_SCRIPTS, TYPE_FOOTER_SCRIPTS, ])(enhance(TextareaField));
src/containers/Todo.js
cyrfer/firestarter
import React from 'react' import PropTypes from 'prop-types' const Todo = ({ onClick, completed, text }) => ( <li onClick={onClick} style={{ textDecoration: completed ? 'line-through' : 'none' }} > {text} </li> ) Todo.propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo
src/interface/icons/PatreonTiny.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; // From the Patreon branding page const Icon = ({ colored, ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 96" className="icon" {...other}> <g fillRule="evenodd"> <path fill={colored ? '#ffffff' : undefined} d="M64.1102,0.1004 C44.259,0.1004 28.1086,16.2486 28.1086,36.0986 C28.1086,55.8884 44.259,71.989 64.1102,71.989 C83.9,71.989 100,55.8884 100,36.0986 C100,16.2486 83.9,0.1004 64.1102,0.1004" /> <polygon fill={colored ? '#F96854' : undefined} points=".012 95.988 17.59 95.988 17.59 .1 .012 .1" /> </g> </svg> ); Icon.propTypes = { colored: PropTypes.bool, }; Icon.defaultProps = { colored: false, }; export default Icon;
node_modules/react-bootstrap/es/Checkbox.js
mohammed52/door-quote-automator
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: PropTypes.bool, disabled: PropTypes.bool, title: PropTypes.string, /** * Only valid if `inline` is not set. */ validationState: PropTypes.oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Checkbox inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: PropTypes.func }; var defaultProps = { inline: false, disabled: false, title: '' }; var Checkbox = function (_React$Component) { _inherits(Checkbox, _React$Component); function Checkbox() { _classCallCheck(this, Checkbox); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Checkbox.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, title = _props.title, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'title', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'checkbox', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Checkbox inline>`. To display ' + 'validation state on an inline checkbox, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style, title: title }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', { title: title }, input, children ) ); }; return Checkbox; }(React.Component); Checkbox.propTypes = propTypes; Checkbox.defaultProps = defaultProps; export default bsClass('checkbox', Checkbox);
docs/src/NotFoundPage.js
xuorig/react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const NotFoundPage = React.createClass({ render() { return ( <div> <NavMain activePage="" /> <PageHeader title="404" subTitle="Hmmm this is awkward." /> <PageFooter /> </div> ); } }); export default NotFoundPage;
docs/Documentation/IconTogglePage.js
reactivers/react-mcw
/** * Created by muratguney on 29/03/2017. */ import React from 'react'; import {Card, CardHeader,IconToggle,Table, TableRow, TableHeaderColumn, TableHeader, TableRowColumn, TableBody} from '../../lib'; import HighLight from 'react-highlight.js' export default class CardPage extends React.Component { render() { let document = ` <IconToggle toggleOffIcon={"add"} toggleOnIcon={"clear"} primary toggleText={"Add/Clear"} /> <IconToggle toggleOffIcon={"menu"} toggleOnIcon={"share"} toggleText={"Menu/Social"} /> `; return ( <Card style={{padding: 8}}> <CardHeader title="Icon Toggle"/> <div style={{display:"flex",justifyContent:"space-around",alignItems:"center"}}> <IconToggle toggleOffIcon={"add"} toggleOnIcon={"clear"} primary toggleText={"Add/Clear"} /> <IconToggle toggleOffIcon={"menu"} toggleOnIcon={"share"} toggleText={"Menu/Social"} /> <IconToggle toggleOffIcon={"menu"} toggleOnIcon={"share"} toggleText={"Menu/Social"} textColor={"red"} accent /> </div> <HighLight source="javascript"> {document} </HighLight> <CardHeader title="IconToggle properties"/> <Table> <TableHeader> <TableRow> <TableHeaderColumn>Props</TableHeaderColumn> <TableHeaderColumn>Type</TableHeaderColumn> <TableHeaderColumn>Description</TableHeaderColumn> </TableRow> </TableHeader> <TableBody> <TableRow> <TableRowColumn>iconColor</TableRowColumn> <TableRowColumn>String</TableRowColumn> <TableRowColumn>Color of icon toggle.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>textColor</TableRowColumn> <TableRowColumn>String</TableRowColumn> <TableRowColumn>Color of text.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>toggleOnIcon</TableRowColumn> <TableRowColumn>String</TableRowColumn> <TableRowColumn>Any material icons.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>toggleOffIcon</TableRowColumn> <TableRowColumn>String</TableRowColumn> <TableRowColumn>Any material icons.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>toggleText</TableRowColumn> <TableRowColumn>String</TableRowColumn> <TableRowColumn>Label of toggle.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>disabled</TableRowColumn> <TableRowColumn>Boolean</TableRowColumn> <TableRowColumn>Disabled swith for icon toggle.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>onStatusChange</TableRowColumn> <TableRowColumn>Function</TableRowColumn> <TableRowColumn>Gives icon toggle status.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>primary</TableRowColumn> <TableRowColumn>Boolean</TableRowColumn> <TableRowColumn>If true, icon toggle gets theme primary color.</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>accent</TableRowColumn> <TableRowColumn>Boolean</TableRowColumn> <TableRowColumn>If true, icon toggle gets theme accent color.</TableRowColumn> </TableRow> </TableBody> </Table> </Card> ) } }
app/components/molecules/TitleBlock/presenter.js
altiore/webpack_config_example
import React from 'react' import FlatButton from 'material-ui/FlatButton' import { NavLink } from 'react-router-dom' import './style.scss' const Title = () => ( <div className='l-header-title'> <div className='b-header-title'> <FlatButton className='b-header-title__button' hoverColor='#fff' containerElement={ <NavLink to='/' activeClassName='active' /> } > <h1>3tarelki.com</h1> <div className='b-header-title__desc'>Кулинарные шедевры на каждый день</div> </FlatButton> </div> </div> ) export default Title
src/elements/Container/Container.js
Semantic-Org/Semantic-UI-React
import cx from 'clsx' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, SUI, useKeyOnly, useTextAlignProp, } from '../../lib' /** * A container limits content to a maximum width. */ function Container(props) { const { children, className, content, fluid, text, textAlign } = props const classes = cx( 'ui', useKeyOnly(text, 'text'), useKeyOnly(fluid, 'fluid'), useTextAlignProp(textAlign), 'container', className, ) const rest = getUnhandledProps(Container, props) const ElementType = getElementType(Container, props) return ( <ElementType {...rest} className={classes}> {childrenUtils.isNil(children) ? content : children} </ElementType> ) } Container.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Container has no maximum width. */ fluid: PropTypes.bool, /** Reduce maximum width to more naturally accommodate text. */ text: PropTypes.bool, /** Align container text. */ textAlign: PropTypes.oneOf(SUI.TEXT_ALIGNMENTS), } export default Container
content/theme/components/Stats/items.js
typesettin/NativeCMS
import React, { Component } from 'react'; import { StyleSheet, Text, View, Platform, ListView, Image, Dimensions, } from 'react-native'; import styles from '../../../../app/components/Styles/shared'; import layoutStyles from '../../../../app/components/Styles/layout'; import Icons from '../../../../app/components/Icons'; import Table from '../../../../app/components/Table'; import LoadingView from '../../../../app/components/LoadingIndicator/LoadingView'; import { Button, } from 'react-native-elements'; import constants from '../../constants'; import ItemDetail from './itemDetail'; import { request, } from '../../../../app/util/request'; class Items extends Component { constructor(props){ super(props); this.state = { itemDataError: false, itemDataLoaded: false, itemData: { itempages: 1, items: [ { title: 'title' }], itemscount: 1, }, }; } componentDidMount() { this.getPipelineIndex(); } getPipelineIndex() { request(constants.pipelines.all.BASE_URL+constants.pipelines.items.GET_INDEX, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Access-Token': this.props.user.jwt_token, }, }) .then(responseData => { this.setState({ itemDataError: false, itemDataLoaded: true, itemData: { itempages: responseData.itempages, items: responseData.items, itemscount: responseData.itemscount, }, }); }) .catch(error => { this.setState({ itemDataError: error, itemDataLoaded: true, }); }); } // componentWillReceiveProps(nextProps) { // console.log('Parsers componentWillRecieveProps nextProps', nextProps); // } render() { let loadingView = (<LoadingView/>); let loadedDataView = ( <Table name="pasdata-items-table" pages={this.state.itemData.itempages} rows={this.state.itemData.items} totalcount={this.state.itemData.itemscount} detailPath="/stats/items/:id" loadExtensionRouteOptions={{ transitionDirection:'right', }} previousExtPath="/stats/items" previousExtloadExtensionRouteOptions={{ transitionDirection:'left', }} {...this.props} > </Table> ); let errorView = ( <View style={styles.container}> <Text style={styles.welcome}>ERROR</Text> </View> ); if (this.state.itemDataLoaded) { if (this.state.itemDataError) { return errorView; } else { return loadedDataView; } } else { return loadingView; } } } export default Items;
lib/ui/src/modules/ui/routes.js
shilman/storybook
import React from 'react'; import ReactDOM from 'react-dom'; import Layout from './containers/layout'; import LeftPanel from './containers/left_panel'; import DownPanel from './containers/down_panel'; import ShortcutsHelp from './containers/shortcuts_help'; import SearchBox from './containers/search_box'; export default function(injectDeps, { clientStore, provider, domNode }) { // generate preview const Preview = () => { const state = clientStore.getAll(); const preview = provider.renderPreview(state.selectedKind, state.selectedStory); return preview; }; const root = ( <div> <Layout leftPanel={() => <LeftPanel />} preview={() => <Preview />} downPanel={() => <DownPanel />} /> <ShortcutsHelp /> <SearchBox /> </div> ); ReactDOM.render(root, domNode); }
src/svg-icons/hardware/developer-board.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDeveloperBoard = (props) => ( <SvgIcon {...props}> <path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"/> </SvgIcon> ); HardwareDeveloperBoard = pure(HardwareDeveloperBoard); HardwareDeveloperBoard.displayName = 'HardwareDeveloperBoard'; HardwareDeveloperBoard.muiName = 'SvgIcon'; export default HardwareDeveloperBoard;
Components/Loader.js
webismymind/Mycelium
import React from 'react'; import Component from './Component'; import { Easing, StyleSheet, Text, View, Animated } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; export default class extends Component { constructor(props) { super(props); this.state = { isVisible : false, style : {}, rotate: new Animated.Value(0), opacity: new Animated.Value(0), spinner : <Icon name="spinner" size={26} color="black" />, message : '' } } componentDidMount() { var runAnimation = () => { this.state.rotate.setValue(0); Animated.timing( this.state.rotate, { toValue: 100, duration: 1500, easing: Easing.linear, useNativeDriver:true } ).start(() => { runAnimation()}); }; runAnimation(); } //Todo Documentation.. setMessage = (message) => { this.setState({message}); }; setStyle = (style) => { //check content.. let autorizedValues = ['overlay', 'box']; for(let i in style) { if (autorizedValues.indexOf(i) < 0) { throw new TypeError('setStyle of Loader only accept '+ JSON.stringify(autorizedValues)); } } this.setState({style:style}); }; setSpinner = (spinner) => { this.setState({spinner:spinner}); }; show = () => { this.setState({isVisible: true}); Animated.timing( this.state.opacity, {toValue: 1, duration: 200,useNativeDriver:true}).start(); }; hide = () => { Animated.timing( this.state.opacity, {toValue: 0, duration: 200,useNativeDriver:true}).start(() => { this.setState({isVisible: false}); }); }; render() { const interpolatedRotateAnimation = this.state.rotate.interpolate({ inputRange: [0, 100], outputRange: ['0deg', '360deg'] }); if( this.state.isVisible) { return ( <Animated.View style={[styles.box, this.state.style.overlay || {}, { opacity: this.state.opacity}]}> <View style={[styles.inner,this.state.style.box || {}]}> <Animated.View style={{alignItems:'center', transform: [{ rotate: interpolatedRotateAnimation }] }}> {this.state.spinner} </Animated.View> {this.state.message !== "" && <Text style={[styles.message,this.state.style.message || {}]}>{this.state.message}</Text>} </View> </Animated.View> ) } else { return null; } } } const styles = StyleSheet.create({ box : { position: 'absolute', top:0, left: 0, backgroundColor:'rgba(0,0,0,.8)', right:0, bottom:0, alignItems:'center', justifyContent:'center' }, inner : { backgroundColor:'white', padding:20, borderRadius:10, }, message : { marginTop:20 }, });
actor-apps/app-web/src/app/index.js
wangkang0627/actor-platform
import crosstab from 'crosstab'; import React from 'react'; import Router from 'react-router'; import Raven from 'utils/Raven'; // eslint-disable-line import isMobile from 'utils/isMobile'; import ReactMixin from 'react-mixin'; import Intl from 'intl'; // eslint-disable-line import LocaleData from 'intl/locale-data/jsonp/en-US'; // eslint-disable-line import { IntlMixin } from 'react-intl'; import { english, russian } from 'l18n'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Deactivated from 'components/Deactivated.react'; import Login from 'components/Login.react'; import Main from 'components/Main.react'; import JoinGroup from 'components/JoinGroup.react'; import Install from 'components/Install.react'; import LoginStore from 'stores/LoginStore'; import LoginActionCreators from 'actions/LoginActionCreators'; //import AppCache from 'utils/AppCache'; // eslint-disable-line import Pace from 'pace'; Pace.start({ ajax: false, restartOnRequestAfter: false, restartOnPushState: false }); const DefaultRoute = Router.DefaultRoute; const Route = Router.Route; const RouteHandler = Router.RouteHandler; const ActorInitEvent = 'concurrentActorInit'; if (crosstab.supported) { crosstab.on(ActorInitEvent, (msg) => { if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') { window.location.assign('#/deactivated'); window.location.reload(); } }); } // Check for mobile device, and force users to install native apps. if (isMobile() && window.location.hash !== '#/install') { window.location.assign('#/install'); document.body.classList.add('overflow'); } else if (window.location.hash === '#/install') { window.location.assign('/'); } @ReactMixin.decorate(IntlMixin) class App extends React.Component { render() { return <RouteHandler/>; } } // Internationalisation // TODO: Move to preferences const language = 'en-US'; //const language = 'ru-RU'; let intlData; switch (language) { case 'ru-RU': intlData = russian; break; case 'en-US': intlData = english; break; } const initReact = () => { if (window.location.hash !== '#/deactivated') { if (crosstab.supported) { crosstab.broadcast(ActorInitEvent, {}); } if (location.pathname === '/app/index.html') { window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']); } else { window.messenger = new window.actor.ActorApp(); } } const routes = ( <Route handler={App} name="app" path="/"> <Route handler={Main} name="main" path="/"/> <Route handler={JoinGroup} name="join" path="/join/:token"/> <Route handler={Login} name="login" path="/auth"/> <Route handler={Deactivated} name="deactivated" path="/deactivated"/> <Route handler={Install} name="install" path="/install"/> <DefaultRoute handler={Main}/> </Route> ); const router = Router.run(routes, Router.HashLocation, function (Handler) { injectTapEventPlugin(); React.render(<Handler {...intlData}/>, document.getElementById('actor-web-app')); }); if (window.location.hash !== '#/deactivated') { if (LoginStore.isLoggedIn()) { LoginActionCreators.setLoggedIn(router, {redirect: false}); } } }; window.jsAppLoaded = () => { setTimeout(initReact, 0); };
src/components/Main.js
linxiuquan/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; // let yeomanImage = require('../images/yeoman.png'); // 获取图片相关的数据 let imageDatas = require('../data/imageDatas.json'); // 利用自执行函数, 将图片名信息转成图片URL路径信息 imageDatas = ((imageDatasArr) => { for(let i = 0, j = imageDatasArr.length; i < j; i++){ let singleImageData = imageDatasArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(imageDatas); /* * 获取区间内的一个随机值 */ const getRangeRandom = (low, high) => { return Math.ceil(Math.random() * (high - low) + low); }; /* * 获取 0~30˚ 之间的一个任意正负值 * */ const get30DegRandom = () => { return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random()*30)); }; class ImgBack extends React.Component{ render(){ return (<p>{this.props.data}</p>); } } class ImgFigure extends React.Component{ /* * imgFigure的点击处理函数 * */ handleClick(e) { if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { let styleObj = {}; // 如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } // 如果图片的旋转角度有值并且补位0,添加旋转角度 if (this.props.arrange.rotate){ (['MozTransForm', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value){ styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } let _desc = this.props.data.desc; function searchSubStr(str,subStr){ let pos = str.indexOf(subStr); while(pos>-1){ positions.push(pos); pos = str.indexOf(subStr,pos+1); } } let positions = new Array(); searchSubStr(_desc,' '); let textList = new Array(); for(let i =0; i<positions.length;i++){ let position = positions[i]; if (i == 0){ textList.push(<ImgBack data={_desc.slice(0,position)}></ImgBack>); if(positions.length==1){ textList.push(<ImgBack data={_desc.slice(position+1,_desc.length)}></ImgBack>); } } else { textList.push(<ImgBack data={_desc.slice(positions[i-1]+1,position)}></ImgBack>); if(i==positions.length-1){ textList.push(<ImgBack data={_desc.slice(positions[i]+1,_desc.length)}></ImgBack>); } } } if (positions.length==0){ textList = _desc; } let imgFigureClassName = 'img-figure' + (this.props.arrange.isInverse ? ' is-inverse' : ''); return ( <figure onClick={this.handleClick.bind(this)} className={imgFigureClassName} style={styleObj} ref="figure"> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick.bind(this)}> {textList} </div> </figcaption> </figure> ); } } // 控制组件 class ControllerUnit extends React.Component{ handleClick(e) { // 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); } render() { let controllerUnitClassName = "controller-unit"; // 如果对应的是居中的图片,显示控制按钮居中态 if (this.props.arrange.isCenter) { controllerUnitClassName += " is-center"; // 如果同时对应的是翻转图片,显示控制按钮的翻转态 if (this.props.arrange.isInverse) { controllerUnitClassName += " is-inverse"; } } return ( <span className={controllerUnitClassName} onClick={this.handleClick.bind(this)}></span> ); } } class AppComponent extends React.Component { constructor(props) { super(props); this.Constant = { centerPos: { left: 0, right: 0 }, hPosRange: { // 水平方向的取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { // 垂直方向的取值范围 x: [0, 0], topY: [0, 0] } }; this.state = { imgsArrangeArr: [ /*{ pos: { left: '0', top: '0' }, rotate: 0, //旋转角度 isInverse: false, // 图片正反面 isCenter: false, // 图片是否居中 }*/ ] } } /* * 利用 rearrange函数,居中对应index的图片 * @param index,需要被居中图片对应的图片信息数组的index值 * @return {Function} */ center(index) { return function () { this.rearrange(index); }.bind(this); } /* * 翻转图片 * @param index 输入当前被执行inverse操作的图片对应的图片信息数组的index值 * @return {Function} 这是一个闭包函数,其内return一个真正待被执行的函数 * */ inverse(index) { return function(){ var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); } /* * 重新布局所有图片 * @param centerindex 指定居中排布那个图片 */ rearrange(centerIndex) { let imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), //取一个或者不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1); // 首先居中 centerIndex 的图片,居中的 centerIndex 的图片不需要旋转 imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true }; // 取出要布局上侧图片的状态信息 topImgSpliceIndex = Math.floor(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum); // 布局位于上侧的图片 imgsArrangeTopArr.forEach((value, index) => { imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false } }); // 布局左右两侧的图片 for (let i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++){ let hPosRangeLORX = null; // 前半部分布局左边,右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate : get30DegRandom(), isCenter: false } } //取出的图片放回去 if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); } // 组件加载以后, 为每张图片计算其位置的范围 componentDidMount() { // 首先拿到舞台的大小 let stageDOM = this.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); // 拿到一个imageFigure的大小 let imgFigureDOM = this.refs.imgFigure0.refs.figure, imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); // 计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; // 计算左侧,右侧区域图片排布位置取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; // 计算上侧区域排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); } render() { let controllerUnits = [], imgFigures = []; imageDatas.forEach(function (value, index) { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, isCenter: false }; } imgFigures.push( <ImgFigure key = {index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index).bind(this)} center={this.center(index).bind(this)}/>); controllerUnits.push( <ControllerUnit key = {index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index).bind(this)} center={this.center(index).bind(this)}/>); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/frontend/components/forms/GCPhoneField.js
al3x/ground-control
import React from 'react'; import {TextField} from 'material-ui'; import {BernieText} from '../styles/bernie-css'; import GCFormField from './GCFormField'; export default class GCPhoneField extends GCFormField { render() { let phone = this.props.value let formattedValue = `(${phone.slice(0, 3)}) ${phone.slice(3,6)}-${phone.slice(6)}` return <TextField {...this.props} value={formattedValue} floatingLabelText={this.floatingLabelText()} errorStyle={BernieText.inputError} hintText={this.props.label} onChange={(event) => { let val = event.target.value.replace(/\D/g,'') this.props.onChange(val) }} /> } }
src/svg-icons/action/lock-open.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLockOpen = (props) => ( <SvgIcon {...props}> <path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z"/> </SvgIcon> ); ActionLockOpen = pure(ActionLockOpen); ActionLockOpen.displayName = 'ActionLockOpen'; ActionLockOpen.muiName = 'SvgIcon'; export default ActionLockOpen;
www/src/index.js
ggerrietts/lemons
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Dashboard from './components/Dashboard'; import reportWebVitals from './reportWebVitals'; import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render( <React.StrictMode> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /> <Dashboard /> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
src/features/IntroModal/Description.js
erhathaway/cellular_automata
import React from 'react'; import styled from 'react-emotion'; const Container = styled('p')` display: flex; justify-content: center; align-items: center; text-align: center; font-size: 15px; color: #7c842a; line-height: 28px; letter-spacing: 5px; text-transform: uppercase; width: 90vw; font-size: 20px; margin-bottom: 50px; margin-top: 50px; height: 50px; @media (max-width: 300px) { margin-bottom: 100px; margin-top: 70px; } `; export default props => ( <Container className="landing-description" {...props}> {'a social cellular automata & generative art experiment'} </Container> );
src/App.js
luiscspinho/twitterManage
import React from 'react'; class App extends React.Component { render(){ let cat = this.props.cat return ( <div> <Title text="Text" /> <NestedH1>Hello World and cat {cat} with Component heart <Heart /> bla bla</NestedH1> </div> ) } } const Title = (props) => <h1>Title: {props.text}</h1> const NestedH1 = (props) => <h1>{props.children}</h1> class Heart extends React.Component { render(){ return <span>&hearts;</span> } } App.defaultProps = { cat: 123 } export default App
webapp/src/components/__tests__/dropdowns/ExpandableMenuItem.spec.js
unicef/rhizome
import React from 'react' import _ from 'lodash' import { expect } from 'chai' import { render, shallow } from 'enzyme' import ExpandableMenuItem from '../../dropdown/ExpandableMenuItem' import sinon from 'sinon' describe ('ExpandableMenuItem', () => { let mockExpandableMenuItem beforeEach (() => { mockExpandableMenuItem = shallow(<ExpandableMenuItem />).instance() }) it ('exists', () => { expect (ExpandableMenuItem).to.exist }) describe ('.propTypes', () => { it ('exists', () => { expect (ExpandableMenuItem.propTypes).to.exist }) it ('has the correct keys', () => { expect (ExpandableMenuItem.propTypes).to.have.all.keys('sendValue', 'title', 'value', 'classes', 'ancestryString', 'children', 'depth', 'disabled', 'filtered', 'displayTitle', 'noValue', 'hideLastLevel') }) }) describe ('.fromArray()', () => { it ('exists', () => { expect (ExpandableMenuItem.fromArray).to.exist }) }) describe ('.getDefaultProps()', () => { it ('exists', () => { expect (ExpandableMenuItem.getDefaultProps).to.exist }) it ('returns correct default key and values', () => { const defaultProps = ExpandableMenuItem.getDefaultProps() const expectedDefaultProps = ExpandableMenuItemTest.getProps() expect (defaultProps).to.have.all.keys('depth', 'filtered', 'hideLastLevel', 'displayTitle') expect (defaultProps.depth).to.eq(expectedDefaultProps.depth) expect (defaultProps.filtered).to.eq(expectedDefaultProps.filtered) expect (defaultProps.hideLastLevel).to.eq(expectedDefaultProps.hideLastLevel) expect (defaultProps.displayTitle).to.eq(expectedDefaultProps.displayTitle) }) }) describe ('.getInitialState()', () => { it ('exists', () =>{ expect (mockExpandableMenuItem.getInitialState).to.exist }) it ('returns correct default key and values', () => { const defaultState = mockExpandableMenuItem.getInitialState() const expectedInitialState = ExpandableMenuItemTest.getState() expect (defaultState).to.have.all.keys('open', 'disabled') expect (defaultState.open).to.eq(expectedInitialState.open) expect (defaultState.disabled).to.eq(expectedInitialState.disabled) }) }) describe ('#componentDidMount()', () => { it ('exists', () => { expect (mockExpandableMenuItem.componentDidMount).to.exist }) it ('sets state for `disabled`', () => { const prototype = ExpandableMenuItem.prototype const spy = sinon.spy(prototype, 'setState') const wrapper = shallow(<ExpandableMenuItem {...ExpandableMenuItemTest.getProps()}/>) wrapper.instance().componentDidMount() prototype.setState.restore() expect (wrapper.instance().state.disabled).to.eq(ExpandableMenuItemTest.getProps().disabled) expect (spy.calledOnce).to.be.true expect (spy.calledWith({disabled: ExpandableMenuItemTest.getProps().disabled})).to.be.true }) }) describe ('#componentWillUpdate()', () => { it ('exists with correct parameters', () => { expect (mockExpandableMenuItem.componentWillUpdate).to.exist.and.have.lengthOf(2) }) context ('when props.disabled not equal to nextProps.disabled', () => { it ('sets state of `disabled` to nextProps.disabled', () => { const prototype = ExpandableMenuItem.prototype const spy = sinon.spy(prototype, 'setState') const props = ExpandableMenuItemTest.getProps() const nextProps = { disabled: !props.disabled } const wrapper = shallow(<ExpandableMenuItem {...props}/>) wrapper.instance().componentWillUpdate(nextProps) prototype.setState.restore() expect (wrapper.instance().state.disabled).to.eq(nextProps.disabled) expect (spy.calledOnce).to.be.true expect (spy.calledWith({disabled: nextProps.disabled})).to.be.true }) it ('sets state of `disabled` to nextProps.disabled', () => { const prototype = ExpandableMenuItem.prototype const spy = sinon.spy(prototype, 'setState') const props = ExpandableMenuItemTest.getProps() const wrapper = shallow(<ExpandableMenuItem {...props}/>) wrapper.instance().componentWillUpdate(props) prototype.setState.restore() expect (wrapper.instance().state.disabled).to.eq(props.disabled) expect (spy.called).to.be.false }) }) }) describe ('#_toggleChildren()', () => { it ('exists with correct parameters', () => { expect (mockExpandableMenuItem._toggleChildren).to.exist.and.have.lengthOf(1) }) it ('calls stopPropagation on event', () => { const spy = sinon.spy() mockExpandableMenuItem._toggleChildren({type: 'keyup', stopPropagation: spy}) expect (spy.calledOnce).to.be.true }) it ('sets state `open` to opposite of current state.open', () => { const prototype = ExpandableMenuItem.prototype const spy = sinon.spy(prototype, 'setState') const props = ExpandableMenuItemTest.getProps() const wrapper = shallow(<ExpandableMenuItem {...props}/>) const state = wrapper.instance().state wrapper.instance()._toggleChildren({type: 'keyup', stopPropagation: () => null}) prototype.setState.restore() expect (wrapper.instance().state.open).to.not.eq(state.open) expect (spy.calledOnce).to.be.true expect (spy.calledWith({open: !state.open})).to.be.true }) }) describe ('#_handleClick()', () => { it ('exists with correct parameters', () => { expect (mockExpandableMenuItem._handleClick).to.exist.and.have.lengthOf(1) }) context ('if props.noValue is false and state.disabled is false', () => { it ('calls props.sendValue and setState', () => { let props = ExpandableMenuItemTest.getProps() const sendValueSpy = sinon.spy() props.sendValue = sendValueSpy props.noValue = false const prototype = ExpandableMenuItem.prototype const setStateSpy = sinon.spy(prototype, 'setState') mockExpandableMenuItem = shallow(<ExpandableMenuItem {...props} />).instance() mockExpandableMenuItem._handleClick({type: 'keyup'}) prototype.setState.restore() expect (sendValueSpy.calledOnce).to.be.true expect (sendValueSpy.calledWith(props.value)).to.be.true expect (setStateSpy.calledOnce).to.be.true expect (setStateSpy.calledWith({disabled: true})).to.be.true }) }) context ('if props.noValue or state.disabled is false', () => { const e = {type: 'keyup', stopPropagation: () => null} it ('calls #_toggleChildren()', () => { let props = ExpandableMenuItemTest.getProps() props.noValue = false const spy = sinon.spy(ExpandableMenuItem.prototype.__reactAutoBindMap, '_toggleChildren') mockExpandableMenuItem = shallow(<ExpandableMenuItem {...props} />).instance() mockExpandableMenuItem.state.disabled = true mockExpandableMenuItem._handleClick(e) const calledOnce = spy.calledOnce const calledWith = spy.calledWith(e) ExpandableMenuItem.prototype.__reactAutoBindMap._toggleChildren.restore() expect (calledOnce).to.be.true expect (calledWith).to.be.true }) it ('calls #_toggleChildren()', () => { let props = ExpandableMenuItemTest.getProps() props.noValue = true const spy = sinon.spy(ExpandableMenuItem.prototype.__reactAutoBindMap, '_toggleChildren') mockExpandableMenuItem = shallow(<ExpandableMenuItem {...props} />).instance() mockExpandableMenuItem.state.disabled = false mockExpandableMenuItem._handleClick(e) ExpandableMenuItem.prototype.__reactAutoBindMap._toggleChildren.restore() expect (spy.calledOnce).to.be.true expect (spy.calledWith(e)).to.be.true }) }) }) describe ('#render()', () => { it ('exists', () => { mockExpandableMenuItem = new ExpandableMenuItem() expect (mockExpandableMenuItem.render).to.exist }) it ('renders correct jsx', () => { const props = ExpandableMenuItemTest.getProps() const actualComponent = shallow(<ExpandableMenuItem {...props}/>).debug() const expectedComponent = shallow(ExpandableMenuItemTest.getComponent()).debug() expect (actualComponent).to.equal(expectedComponent) }) }) }) class ExpandableMenuItemTest { static getProps() { return { disabled: false, depth: 0, filtered: false, hideLastLevel: false, displayTitle: null, classes: '', onClick: this._handleClick, } } static getState() { return { open: false, disabled: false } } static _handleClick() { return null } static getComponent() { const props = this.getProps() let state = this.getState() const hasChildren = !props.filtered && _.isArray(props.children) && props.children.length > 0 const isLastParent = props.children && props.children.filter(child => child.children).length < 1 const hideArrow = isLastParent && props.hideLastLevel const prefix = props.filtered ? _.get(props, 'ancestryString', '') : '' const title = prefix + (props.displayTitle === null ? props.title : props.displayTitle) var children = null if (props.children && state.open) { children = props.children.map(item => { return <MenuItem key={item.value} depth={props.depth + 1} sendValue={props.sendValue} {...item} hideLastLevel={props.hideLastLevel}/> }) } var arrowStyle = { paddingLeft: state.filtered ? '5px' : (5 + (17 * props.depth)) + 'px', display: 'inline-block' } const arrow_button = hasChildren ? ( <a onClick={this._toggleChildren} className={hasChildren ? 'folder' : null} style={arrowStyle}> <i className={'fa fa-lg fa-fw fa-caret-' + (state.open ? 'down' : 'right')}></i> </a> ) : null let itemStyle = { display: 'inline-block' } let classes = state.disabled ? ' disabled ' : '' classes += hasChildren ? 'folder' : '' !hasChildren || hideArrow ? itemStyle.paddingLeft = state.filtered ? '5px' : (15 + (18 * props.depth)) + 'px' : null const item_button = ( <a role='menuitem' onClick={this._handleClick} style={itemStyle} tabIndex='-1' className={classes} > {title} </a> ) return ( <li className={props.classes}> { hideArrow ? null : arrow_button } { item_button } <div> {children} </div> </li> ) } }
src/index.js
domark0721/Redux-TodoList-Official
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import App from './containers/App' import todoApp from './reducers/reducers' // create a store let store = createStore(todoApp) let rootElement = document.getElementById('root'); render( <Provider store={store} > <App /> </Provider>, rootElement ) // ReactDOM.render(<App />, document.getElementById('root'));
frontend/src/components/Dialogs/CreatePostDialog.js
kiok46/Readable
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; class CreatePostDialog extends Component { state= { open: false, } openEditDialog = () => { }; openDeleteDialog = () => { }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onClick={this.handleClose} />, <FlatButton label="Submit" primary={true} keyboardFocused={true} onClick={this.handleClose} />, ]; return ( <Dialog title="Create a Post" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > The actions in this window were passed in as an array of React objects. </Dialog> ) } } const styles = { actionButtonStyle: { margin: 12, }, wrapper: { display: 'flex', flexWrap: 'wrap', margin: 10, }, chip: { margin: 10, paddingTop: 3, }, root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, gridList: { width: 500, height: 450, overflowY: 'auto', }, }; CreatePostDialog.defaultProps = { } CreatePostDialog.propTypes = { } export default CreatePostDialog;
src/web/containers/HomePage/index.js
lukemarsh/react-redux-boilerplate
/* * HomePage * * This is the first thing users see of our App, at the '/' route */ import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import messages from 'core/HomePage/messages'; import { createStructuredSelector } from 'reselect'; import { selectRepos, selectLoading, selectError, selectCurrentUser } from 'core/App/selectors'; import { selectUsername } from 'core/HomePage/selectors'; import { changeUsername } from 'core/HomePage/actions'; import { loadRepos } from 'core/App/actions'; import RepoListItem from 'web/components/RepoListItem'; import List from 'web/components/List'; import ListItem from 'web/components/ListItem'; import LoadingIndicator from 'web/components/LoadingIndicator'; import styles from './styles.css'; export const HomePage = (props) => { const { username, loading, error, repos, currentUser, onSubmitForm, onChangeUsername } = props; let mainContent = null; // Show a loading indicator when we're loading if (loading) { mainContent = (<List component={LoadingIndicator} />); // Show an error if there is one } else if (error !== false) { const ErrorComponent = () => ( <ListItem item={'Something went wrong, please try again!'} /> ); mainContent = (<List component={ErrorComponent} />); // If we're not loading, don't have an error and there are repos, show the repos } else if (repos !== false) { mainContent = (<List items={repos} currentUser={currentUser} component={RepoListItem} />); } return ( <article> <Helmet title="Home Page" meta={[ { name: 'description', content: 'A React.js Boilerplate application homepage' }, ]} /> <div> <section className={`${styles.textSection} ${styles.centered}`}> <h2> {messages.startProjectHeader} </h2> <p> {messages.startProjectMessage} </p> </section> <section className={styles.textSection}> <h2> {messages.trymeHeader} </h2> <form className={styles.usernameForm} onSubmit={onSubmitForm}> <label htmlFor="username"> {messages.trymeMessage} <span className={styles.atPrefix}> {messages.trymeAtPrefix} </span> <input id="username" className={styles.input} type="text" placeholder="lukemarsh" value={username} onChange={onChangeUsername} /> </label> </form> {mainContent} </section> </div> </article> ); }; HomePage.propTypes = { loading: React.PropTypes.bool, error: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), repos: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.bool, ]), currentUser: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.string ]), onSubmitForm: React.PropTypes.func, username: React.PropTypes.string, onChangeUsername: React.PropTypes.func, }; export function mapDispatchToProps(dispatch) { return { onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)), onSubmitForm: (evt) => { if (evt !== undefined && evt.preventDefault) evt.preventDefault(); dispatch(loadRepos()); }, dispatch, }; } const mapStateToProps = createStructuredSelector({ repos: selectRepos(), username: selectUsername(), loading: selectLoading(), error: selectError(), currentUser: selectCurrentUser() }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
src/svg-icons/action/shop.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShop = (props) => ( <SvgIcon {...props}> <path d="M16 6V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H2v13c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6h-6zm-6-2h4v2h-4V4zM9 18V9l7.5 4L9 18z"/> </SvgIcon> ); ActionShop = pure(ActionShop); ActionShop.displayName = 'ActionShop'; ActionShop.muiName = 'SvgIcon'; export default ActionShop;
components/Notification/components/List/Item.js
yabeow/sinhvienuit
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardItem, Text, Button, Icon, Badge, Left, Right, Body } from 'native-base'; import Navigator from '../../../Navigator/Action'; const renderSource = (source) => { if (source === 'DAA') { return ( <Badge primary> <Text>DAA</Text> </Badge> ); } else if (source === 'OEP') { return ( <Badge info> <Text>OEP</Text> </Badge> ); } return ( <Badge success> <Text>ORTHER</Text> </Badge> ); }; const renderType = (type) => { if (type === 1) { return ( <Badge warning> <Text>Học bù</Text> </Badge> ); } else if (type === 2) { return ( <Badge success> <Text>Nghỉ học</Text> </Badge> ); } return ( <Badge dark> <Text>Chuyển phòng</Text> </Badge> ); }; class Item extends React.Component { render() { const { notification } = this.props; return ( <Card style={{ borderRadius: 8, overflow: 'hidden' }}> <CardItem> <Body> <Text style={{ paddingTop: 10 }}>{notification.getTitle()}</Text> <Text note> {notification.getCreateTime('L')} </Text> </Body> </CardItem> {!!notification.code && ( <CardItem style={{ paddingTop: 2 }}> <Icon name="home" /> <Text>Phòng học: {notification.getRoom()}</Text> </CardItem> )} {!!notification.code && ( <CardItem style={{ paddingTop: 2 }}> <Icon name="time" /> <Text> Thời gian: {notification.getStartTime('LT')} - {notification.getEndTime('LT')} </Text> </CardItem> )} <CardItem style={{ paddingTop: 2 }}> <Left> {renderSource(this.props.notification.getSource())} {!!notification.code && renderType(notification.getType())} </Left> <Body /> <Right> <Button rounded small onPress={() => Navigator.navigate('WebBrowser', { link: notification.getLink() })} success > <Icon name="exit" /> <Text>Xem</Text> </Button> </Right> </CardItem> </Card> ); } } Item.propTypes = { notification: PropTypes.object.isRequired, }; export default Item;
react-fundamentals-es6/lessons/05-owner-ownee/main.js
wandarkaf/React-Bible
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
src/templates/index-template.js
renegens/blog
// @flow strict import React from 'react'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import Sidebar from '../components/Sidebar'; import Feed from '../components/Feed'; import Page from '../components/Page'; import Pagination from '../components/Pagination'; import { useSiteMetadata } from '../hooks'; import type { PageContext, AllMarkdownRemark } from '../types'; type Props = { data: AllMarkdownRemark, pageContext: PageContext }; const IndexTemplate = ({ data, pageContext }: Props) => { const { title: siteTitle, subtitle: siteSubtitle } = useSiteMetadata(); const { currentPage, hasNextPage, hasPrevPage, prevPagePath, nextPagePath } = pageContext; const { edges } = data.allMarkdownRemark; const pageTitle = currentPage > 0 ? `Posts - Page ${currentPage} - ${siteTitle}` : siteTitle; return ( <Layout title={pageTitle} description={siteSubtitle}> <Sidebar isIndex /> <Page> <Feed edges={edges} /> <Pagination prevPagePath={prevPagePath} nextPagePath={nextPagePath} hasPrevPage={hasPrevPage} hasNextPage={hasNextPage} /> </Page> </Layout> ); }; export const query = graphql` query IndexTemplate($postsLimit: Int!, $postsOffset: Int!) { allMarkdownRemark( limit: $postsLimit, skip: $postsOffset, filter: { frontmatter: { template: { eq: "post" }, draft: { ne: true } } }, sort: { order: DESC, fields: [frontmatter___date] } ){ edges { node { fields { slug categorySlug } frontmatter { title date category description } } } } } `; export default IndexTemplate;
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/Well.js
OpenKGB/webcode
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, bsSizes, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; var Well = function (_React$Component) { _inherits(Well, _React$Component); function Well() { _classCallCheck(this, Well); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Well.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Well; }(React.Component); export default bsClass('well', bsSizes([Size.LARGE, Size.SMALL], Well));
src/svg-icons/image/assistant-photo.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAssistantPhoto = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ImageAssistantPhoto = pure(ImageAssistantPhoto); ImageAssistantPhoto.displayName = 'ImageAssistantPhoto'; ImageAssistantPhoto.muiName = 'SvgIcon'; export default ImageAssistantPhoto;
docs/app/Examples/collections/Table/Variations/TableExampleBasic.js
ben174/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleBasic = () => { return ( <Table basic> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleBasic
webapp/src/ViewGame.js
erwannT/go-dart
import React, { Component } from 'react'; import logo from './logo.svg'; import Player from './Player'; import NewPlayerButton from './NewPlayerButton'; import NowPlaying from './NowPlaying'; import PlayerList from './PlayerList'; import NextPlayerButton from './NextPlayerButton' import Congratulation from './Congratulation' class ViewGame extends Component { constructor(props) { super(props) this.state = { gameId: props.params.gameId, Players: [] } console.log("fetching game " + this.state.gameId) } componentDidMount() { console.log("fetching games") fetch('/api/games/' + this.state.gameId) .then((response) => response.json()) .then((json) => this.updateGameState(json.game)) .catch((error) => console.log(error)) var wsProtocol = "wss"; if (window.location.protocol == "http:") { // keep using non secured connection wsProtocol = "ws"; } this.ws = new WebSocket(wsProtocol + '://' + window.location.host + '/api/games/' + this.state.gameId + '/ws'); this.ws.onmessage = (event) => this.updateGameState(JSON.parse(event.data)) } updateGameState(game) { this.setState({ game: game }) } render() { const {gameId} = this.props.params const {game} = this.state if (!game) { return null } const players = (game.Players ? game.Players.map((player) => <Player key={player.Name} player={player}/>) : []) // Display NewPlayerButton only if ongoing is INITIALIZING or READY const newPlayerButton = (game.Ongoing <= 1 ? <NewPlayerButton gameId={ gameId }/> : "") const playerPanel = (game.Ongoing == 4 ? <Congratulation game={ game } player={ game.Players[game.CurrentPlayer]} > </Congratulation> : <NowPlaying gameId={ gameId } game={ game } player={ game.Players[game.CurrentPlayer]}/>) return ( <div> <div className="row"> <h2 className="col s12 l6 offset-l3"><img src={logo} className="App-logo" style={{'vertical-align': 'middle'}} alt="logo" /><span style={{'vertical-align': 'middle'}} >Game #{ gameId }</span></h2> </div> <div className="row"> <div className="col s12 l6 offset-l3"> {newPlayerButton} </div> <div className="col s12 l6 offset-l3"> {playerPanel} </div> <div className="col s12 l6 offset-l3"> <PlayerList game={ game } players={ game.Players}/> </div> </div> </div> ); } } export default ViewGame;
client/src/components/Pagination.js
EspelhoPolitico/espelhopolitico
import { Icon, Menu } from 'semantic-ui-react'; import React from 'react'; export default class Pagination extends React.Component { constructor(props) { super(props); this.handleItemClick = this.handleItemClick.bind(this); this.handleGoToPage = this.handleGoToPage.bind(this); } handleItemClick(e, { name }) { let page = parseInt(name, 10); this.props.onPageChange(page); } handleGoToPage(page) { this.props.onPageChange(page); } render() { let { numberOfPages, currentPage } = this.props; let pagination = () => { let items = []; let firstPage = (currentPage < 3) ? 1 : currentPage - 2; let visiblePages = (numberOfPages < 5) ? numberOfPages : 5; if ((numberOfPages - firstPage) < visiblePages) { firstPage = numberOfPages - visiblePages + 1; } let lastPage = firstPage + (visiblePages - 1); for (let i = firstPage; i <= lastPage; i++) { if (i === currentPage) { items.push(<Menu.Item key={i} active={true} disabled>{i}</Menu.Item>); } else { items.push( <Menu.Item key={i} name={i.toString()} onClick={this.handleItemClick} /> ); } } if (items.length) { return ( <Menu pagination size='small'> {currentPage > firstPage && <Menu.Item link onClick={() => this.handleGoToPage(currentPage - 1)} > <Icon fitted name='angle left' /> </Menu.Item> } {items} {currentPage < lastPage && <Menu.Item link onClick={() => this.handleGoToPage(currentPage + 1)} > <Icon fitted name='angle right' /> </Menu.Item> } </Menu> ); } } return ( <div> {pagination()} </div> ); } }
src/svg-icons/hardware/videogame-asset.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareVideogameAsset = (props) => ( <SvgIcon {...props}> <path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-10 7H8v3H6v-3H3v-2h3V8h2v3h3v2zm4.5 2c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4-3c-.83 0-1.5-.67-1.5-1.5S18.67 9 19.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); HardwareVideogameAsset = pure(HardwareVideogameAsset); HardwareVideogameAsset.displayName = 'HardwareVideogameAsset'; export default HardwareVideogameAsset;
actor-apps/app-web/src/app/components/Login.react.js
VikingDen/actor-platform
import _ from 'lodash'; import React from 'react'; import classNames from 'classnames'; import { Styles, RaisedButton, TextField } from 'material-ui'; import { AuthSteps } from 'constants/ActorAppConstants'; import Banner from 'components/common/Banner.react'; import LoginActionCreators from 'actions/LoginActionCreators'; import LoginStore from 'stores/LoginStore'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = function () { return ({ step: LoginStore.getStep(), errors: LoginStore.getErrors(), smsRequested: LoginStore.isSmsRequested(), signupStarted: LoginStore.isSignupStarted(), codeSent: false }); }; class Login extends React.Component { static contextTypes = { router: React.PropTypes.func }; static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { LoginStore.removeChangeListener(this.onChange); } componentDidMount() { this.handleFocus(); } componentDidUpdate() { this.handleFocus(); } constructor(props) { super(props); this.state = _.assign({ phone: '', name: '', code: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); if (LoginStore.isLoggedIn()) { window.setTimeout(() => this.context.router.replaceWith('/'), 0); } else { LoginStore.addChangeListener(this.onChange); } } onChange = () => { this.setState(getStateFromStores()); } onPhoneChange = event => { this.setState({phone: event.target.value}); } onCodeChange = event => { this.setState({code: event.target.value}); } onNameChange = event => { this.setState({name: event.target.value}); } onRequestSms = event => { event.preventDefault(); LoginActionCreators.requestSms(this.state.phone); } onSendCode = event => { event.preventDefault(); LoginActionCreators.sendCode(this.context.router, this.state.code); } onSignupRequested = event => { event.preventDefault(); LoginActionCreators.sendSignup(this.context.router, this.state.name); } onWrongNumberClick = event => { event.preventDefault(); LoginActionCreators.wrongNumberClick(); } handleFocus = () => { switch (this.state.step) { case AuthSteps.PHONE_WAIT: this.refs.phone.focus(); break; case AuthSteps.CODE_WAIT: this.refs.code.focus(); break; case AuthSteps.SIGNUP_NAME_WAIT: this.refs.name.focus(); break; default: return; } } render() { let requestFormClassName = classNames('login__form', 'login__form--request', { 'login__form--done': this.state.step > AuthSteps.PHONE_WAIT, 'login__form--active': this.state.step === AuthSteps.PHONE_WAIT }); let checkFormClassName = classNames('login__form', 'login__form--check', { 'login__form--done': this.state.step > AuthSteps.CODE_WAIT, 'login__form--active': this.state.step === AuthSteps.CODE_WAIT }); let signupFormClassName = classNames('login__form', 'login__form--signup', { 'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT }); return ( <section className="login-new row center-xs middle-xs"> <Banner/> <div className="login-new__welcome col-xs row center-xs middle-xs"> <img alt="Actor messenger" className="logo" src="assets/img/logo.png" srcSet="assets/img/[email protected] 2x"/> <article> <h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1> <p> Actor Messenger brings all your business network connections into one place, makes it easily accessible wherever you go. </p> <p> Our aim is to make your work easier, reduce your email amount, make the business world closer by reducing time to find right contacts. </p> </article> <footer> <div className="pull-left"> Actor Messenger © 2015 </div> <div className="pull-right"> <a href="//actor.im/ios">iPhone</a> <a href="//actor.im/android">Android</a> </div> </footer> </div> <div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs"> <div> <h1 className="login-new__heading">Sign in</h1> <form className={requestFormClassName} onSubmit={this.onRequestSms}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.PHONE_WAIT} errorText={this.state.errors.phone} floatingLabelText="Phone number" onChange={this.onPhoneChange} ref="phone" type="text" value={this.state.phone}/> <footer className="text-center"> <RaisedButton label="Request code" type="submit"/> </footer> </form> <form className={checkFormClassName} onSubmit={this.onSendCode}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.CODE_WAIT} errorText={this.state.errors.code} floatingLabelText="Auth code" onChange={this.onCodeChange} ref="code" type="text" value={this.state.code}/> <footer className="text-center"> <RaisedButton label="Check code" type="submit"/> </footer> </form> <form className={signupFormClassName} onSubmit={this.onSignupRequested}> <TextField className="login__form__input" errorText={this.state.errors.signup} floatingLabelText="Your name" onChange={this.onNameChange} ref="name" type="text" value={this.state.name}/> <footer className="text-center"> <RaisedButton label="Sign up" type="submit"/> </footer> </form> </div> </div> </section> ); } } export default Login;
packages/wix-style-react/src/MessageModalLayout/docs/index.story.js
wix/wix-style-react
import React from 'react'; import { header, tabs, tab, description, importExample, title, divider, example, playground, api, testkit, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import MessageModalLayout from '..'; import Checkbox from '../../Checkbox'; import SimpleExample from '!raw-loader!./examples/SimpleExample'; import BasicExample from '!raw-loader!./examples/BasicExample'; import FootnoteExample from '!raw-loader!./examples/FootnoteExample'; import IllustrationExample from '!raw-loader!./examples/IllustrationExample'; import DestructiveThemeExample from '!raw-loader!./examples/DestructiveThemeExample'; import ThemeExample from '!raw-loader!./examples/ThemeExample'; import HelpButtonExample from '!raw-loader!./examples/HelpButtonExample'; export default { category: storySettings.category, storyName: storySettings.storyName, component: MessageModalLayout, componentPath: '..', componentProps: { title: 'Modal title', children: 'Lorem ipsum', primaryButtonText: 'Confirm', secondaryButtonText: 'Cancel', sideActions: <Checkbox>Check</Checkbox>, footnote: 'footnote text', onCloseButtonClick: () => {}, }, exampleProps: {}, sections: [ header({ sourceUrl: 'https://github.com/wix/wix-style-react/tree/master/src/MessageModalLayout/', }), tabs([ tab({ title: 'Description', sections: [ description({ title: 'Description', text: 'Use this component inside a Modal to display content in the MessageModalLayout. You may place a title and/or a footer with actions relevant to the displayed content', }), importExample( "import { MessageModalLayout } from 'wix-style-react';", ), divider(), title('Examples'), example({ title: 'Opening a modal', text: 'Use Modal component to reveal the message modal layout.', source: SimpleExample, }), example({ title: 'Simple Usage', text: 'A simple example with compact preview', source: BasicExample, }), example({ title: 'Footnote Example', description: 'A simple example with Footnote', source: FootnoteExample, }), example({ title: 'Help Button Example', text: 'A simple example with a help button shown', source: HelpButtonExample, }), example({ title: 'Illustration Example', description: 'A simple example with illustration', source: IllustrationExample, }), example({ title: 'Destructive Theme Example', description: 'A simple example with destructive theme and illustration', source: DestructiveThemeExample, }), example({ title: 'Premium Theme Example', text: 'A simple example with premium theme and illustration', source: ThemeExample, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };
app/javascript/mastodon/features/compose/components/privacy_dropdown.js
pfm-eyesightjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, defineMessages } from 'react-intl'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ public_short: { id: 'privacy.public.short', defaultMessage: 'Public' }, public_long: { id: 'privacy.public.long', defaultMessage: 'Post to public timelines' }, unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' }, unlisted_long: { id: 'privacy.unlisted.long', defaultMessage: 'Do not show in public timelines' }, private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' }, private_long: { id: 'privacy.private.long', defaultMessage: 'Post to followers only' }, direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' }, direct_long: { id: 'privacy.direct.long', defaultMessage: 'Post to mentioned users only' }, change_privacy: { id: 'privacy.change', defaultMessage: 'Adjust status privacy' }, }); const iconStyle = { height: null, lineHeight: '27px', }; @injectIntl export default class PrivacyDropdown extends React.PureComponent { static propTypes = { isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onModalOpen: PropTypes.func, onModalClose: PropTypes.func, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: false, }; handleToggle = () => { if (this.props.isUserTouching()) { if (this.state.open) { this.props.onModalClose(); } else { this.props.onModalOpen({ actions: this.options.map(option => ({ ...option, active: option.value === this.props.value })), onClick: this.handleModalActionClick, }); } } else { this.setState({ open: !this.state.open }); } } handleModalActionClick = (e) => { e.preventDefault(); const { value } = this.options[e.currentTarget.getAttribute('data-index')]; this.props.onModalClose(); this.props.onChange(value); } handleClick = (e) => { if (e.key === 'Escape') { this.setState({ open: false }); } else if (!e.key || e.key === 'Enter') { const value = e.currentTarget.getAttribute('data-index'); e.preventDefault(); this.setState({ open: false }); this.props.onChange(value); } } onGlobalClick = (e) => { if (e.target !== this.node && !this.node.contains(e.target) && this.state.open) { this.setState({ open: false }); } } componentWillMount () { const { intl: { formatMessage } } = this.props; this.options = [ { icon: 'globe', value: 'public', text: formatMessage(messages.public_short), meta: formatMessage(messages.public_long) }, { icon: 'unlock-alt', value: 'unlisted', text: formatMessage(messages.unlisted_short), meta: formatMessage(messages.unlisted_long) }, { icon: 'lock', value: 'private', text: formatMessage(messages.private_short), meta: formatMessage(messages.private_long) }, { icon: 'envelope', value: 'direct', text: formatMessage(messages.direct_short), meta: formatMessage(messages.direct_long) }, ]; } componentDidMount () { window.addEventListener('click', this.onGlobalClick); window.addEventListener('touchstart', this.onGlobalClick); } componentWillUnmount () { window.removeEventListener('click', this.onGlobalClick); window.removeEventListener('touchstart', this.onGlobalClick); } setRef = (c) => { this.node = c; } render () { const { value, intl } = this.props; const { open } = this.state; const valueOption = this.options.find(item => item.value === value); return ( <div ref={this.setRef} className={`privacy-dropdown ${open ? 'active' : ''}`}> <div className='privacy-dropdown__value'><IconButton className='privacy-dropdown__value-icon' icon={valueOption.icon} title={intl.formatMessage(messages.change_privacy)} size={18} expanded={open} active={open} inverted onClick={this.handleToggle} style={iconStyle} /></div> <div className='privacy-dropdown__dropdown'> {open && this.options.map(item => <div role='button' tabIndex='0' key={item.value} data-index={item.value} onKeyDown={this.handleClick} onClick={this.handleClick} className={`privacy-dropdown__option ${item.value === value ? 'active' : ''}`}> <div className='privacy-dropdown__option__icon'><i className={`fa fa-fw fa-${item.icon}`} /></div> <div className='privacy-dropdown__option__content'> <strong>{item.text}</strong> {item.meta} </div> </div> )} </div> </div> ); } }
fields/types/select/SelectField.js
udp/keystone
import _ from 'underscore'; import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on underscore * - Custom path support */ module.exports = Field.create({ displayName: 'SelectField', valueChanged (newValue) { // TODO: This should be natively handled by the Select component if (this.props.numeric && 'string' === typeof newValue) { newValue = newValue ? Number(newValue) : undefined; } this.props.onChange({ path: this.props.path, value: newValue }); }, renderValue () { var selected = _.findWhere(this.props.ops, { value: this.props.value }); return <FormInput noedit>{selected ? selected.label : null}</FormInput>; }, renderField () { // TODO: This should be natively handled by the Select component var ops = (this.props.numeric) ? this.props.ops.map(function(i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops; var value = ('number' === typeof this.props.value) ? String(this.props.value) : this.props.value; return <Select name={this.props.path} value={value} options={ops} onChange={this.valueChanged} />; } });
src/parser/warrior/arms/modules/talents/SecondWind.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatThousands } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import SpellLink from 'common/SpellLink'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; /** * Restores 6% health every 1 sec when you have not taken damage for 5 sec. */ class SecondWind extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SECOND_WIND_TALENT.id); } subStatistic() { const secondWind = this.abilityTracker.getAbility(SPELLS.SECOND_WIND_TALENT_HEAL.id); const heal = secondWind.healingEffective || 0; return ( <StatisticListBoxItem title={<><SpellLink id={SPELLS.SECOND_WIND_TALENT.id} /> health restored</>} value={formatThousands(heal)} /> ); } } export default SecondWind;
src/elements/rail.js
jessy1092/react-semantify
import React from 'react'; import filter from '../filter'; import Div from '../commons/div'; const defaultClassName = 'ui rail'; const componentName = 'Rail'; const Rail = new filter(Div) .classGenerator(defaultClassName) .getComposeComponent(componentName); export default Rail;
src/svg-icons/image/crop-portrait.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropPortrait = (props) => ( <SvgIcon {...props}> <path d="M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H7V5h10v14z"/> </SvgIcon> ); ImageCropPortrait = pure(ImageCropPortrait); ImageCropPortrait.displayName = 'ImageCropPortrait'; ImageCropPortrait.muiName = 'SvgIcon'; export default ImageCropPortrait;
app/components/Sidebar/Sidebar.js
stephencorwin/stephencorwin.me
import React from 'react'; import PropTypes from 'prop-types'; import RouteShape from '../../prop-types/Route'; import { Header } from './styles'; import A from '../A'; export const Sidebar = ({ headerRoute, className, children }) => ( <aside className={className}> <If condition={headerRoute}> <Header> <A href={headerRoute.href} title={headerRoute.label}> {headerRoute.label} </A> </Header> </If> {children} </aside> ); Sidebar.propTypes = { headerRoute: RouteShape, className: PropTypes.string, children: PropTypes.node }; Sidebar.defaultProps = { headerRoute: undefined, className: '', children: undefined }; export default Sidebar;
client/src/components/recipe/Create.js
noinc/SimpleStorefront
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import Form from './Form'; import { create, reset } from '../../actions/recipe/create'; class Create extends Component { static propTypes = { error: PropTypes.string, loading: PropTypes.bool.isRequired, created: PropTypes.object, create: PropTypes.func.isRequired, reset: PropTypes.func.isRequired }; componentWillUnmount() { this.props.reset(); } render() { if (this.props.created) return ( <Redirect to={`edit/${encodeURIComponent(this.props.created['@id'])}`} /> ); return ( <div> <h1>New Recipe</h1> {this.props.loading && ( <div className="alert alert-info" role="status"> Loading... </div> )} {this.props.error && ( <div className="alert alert-danger" role="alert"> <span className="fa fa-exclamation-triangle" aria-hidden="true" />{' '} {this.props.error} </div> )} <Form onSubmit={this.props.create} values={this.props.item} /> <Link to="." className="btn btn-primary"> Back to list </Link> </div> ); } } const mapStateToProps = state => { const { created, error, loading } = state.recipe.create; return { created, error, loading }; }; const mapDispatchToProps = dispatch => ({ create: values => dispatch(create(values)), reset: () => dispatch(reset()) }); export default connect( mapStateToProps, mapDispatchToProps )(Create);
storybook/stories/HomeTermBarStory.js
ujwalramesh/REHU-discourse
/* @flow */ 'use strict' import React from 'react' import { View } from 'react-native' import { storiesOf } from '@kadira/react-native-storybook' import HomeTermBar from '../../js/components/home/HomeTermBar' storiesOf('HomeTermBar') .addDecorator((story) => ( <View style={{marginTop: 20}}>{story()}</View> )) .add('Collapsed', () => { return ( <HomeTermBar expanded={false} onDidSubmitTerm={(term)=>console.warn('didSubmitTerm', term)} /> ) }) .add('Expanded', () => { return ( <HomeTermBar expanded={true} onDidSubmitTerm={(term)=>console.warn('didSubmitTerm', term)} /> ) })