path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
client/vehicle-finder-spa/src/containers/navbar.js
Del7a/vehicle-finder
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { logout } from '../actions/user'; import NavbarComponent from '../components/navbar'; import { bindActionCreators } from 'redux'; import { Redirect } from 'react-router' class Navbar extends Component { render(){ const isLoggedIn = this.props.user.isLoggedIn || localStorage.getItem("userIsLogged") === '1'; const admin = localStorage.getItem("userIsAdmin") === '1'; return( <NavbarComponent isLoggedIn={isLoggedIn} isAdmin={admin} logout={this.props.logout} handleSearch={this.handleSearch} > </NavbarComponent> )} } function mapStateToProps({user}) { console.log(user) return {user}; } function mapDispatchToProps(dispatch) { return bindActionCreators({logout}, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
src/master.js
m2wasabi/team_vote_milkcocoa
/** * Created by m2wasabi on 2016/07/19. */ import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux' // components import masterApp from './reduces/masterApp'; import App from './components/master/App'; let store = createStore(masterApp); let View = App; /* const View = React.createClass({ render() { return ( <div> ごもくそば! </div> ) } }); */ render( <Provider store={store}> <View/> </Provider>, document.getElementById('content') );
node_modules/recompose/es/Recompose.js
firdiansyah/crud-req
import React, { Component } from 'react'; import shallowEqual from 'fbjs/lib/shallowEqual'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { createChangeEmitter } from 'change-emitter'; import $$observable from 'symbol-observable'; var getDisplayName = function getDisplayName(Component$$1) { if (typeof Component$$1 === 'string') { return Component$$1; } if (!Component$$1) { return undefined; } return Component$$1.displayName || Component$$1.name || 'Component'; }; var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) { return hocName + '(' + getDisplayName(BaseComponent) + ')'; }; var createHelper = function createHelper(func, helperName) { var setDisplayName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var noArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (process.env.NODE_ENV !== 'production' && setDisplayName) { if (noArgs) { return function (BaseComponent) { var Component$$1 = func(BaseComponent); Component$$1.displayName = wrapDisplayName(BaseComponent, helperName); return Component$$1; }; } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return function (BaseComponent) { var Component$$1 = func.apply(undefined, args)(BaseComponent); Component$$1.displayName = wrapDisplayName(BaseComponent, helperName); return Component$$1; }; }; } return func; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var createEagerElementUtil = function createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children) { if (!hasKey && isReferentiallyTransparent) { if (children) { return type(_extends({}, props, { children: children })); } return type(props); } var Component$$1 = type; if (children) { return React.createElement( Component$$1, props, children ); } return React.createElement(Component$$1, props); }; var isClassComponent = function isClassComponent(Component$$1) { return Boolean(Component$$1 && Component$$1.prototype && typeof Component$$1.prototype.isReactComponent === 'object'); }; var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component$$1) { return Boolean(typeof Component$$1 === 'function' && !isClassComponent(Component$$1) && !Component$$1.defaultProps && !Component$$1.contextTypes && (process.env.NODE_ENV === 'production' || !Component$$1.propTypes)); }; var createFactory = function createFactory(type) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); return function (p, c) { return createEagerElementUtil(false, isReferentiallyTransparent, type, p, c); }; }; var mapProps = function mapProps(propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (props) { return factory(propsMapper(props)); }; }; }; var mapProps$1 = createHelper(mapProps, 'mapProps'); var withProps = function withProps(input) { return mapProps$1(function (props) { return _extends({}, props, typeof input === 'function' ? input(props) : input); }); }; var withProps$1 = createHelper(withProps, 'withProps'); var pick = function pick(obj, keys) { var result = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (obj.hasOwnProperty(key)) { result[key] = obj[key]; } } return result; }; var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) { return !shallowEqual(pick(props, shouldMapOrKeys), pick(nextProps, shouldMapOrKeys)); }; return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (shouldMap(this.props, nextProps)) { this.computedProps = propsMapper(nextProps); } }; _class2.prototype.render = function render() { return factory(_extends({}, this.props, this.computedProps)); }; return _class2; }(Component); }; }; var withPropsOnChange$1 = createHelper(withPropsOnChange, 'withPropsOnChange'); var mapValues = function mapValues(obj, func) { var result = {}; /* eslint-disable no-restricted-syntax */ for (var key in obj) { if (obj.hasOwnProperty(key)) { result[key] = func(obj[key], key); } } /* eslint-enable no-restricted-syntax */ return result; }; var withHandlers = function withHandlers(handlers) { return function (BaseComponent) { var _class, _temp2, _initialiseProps; var factory = createFactory(BaseComponent); return _temp2 = _class = function (_Component) { inherits(_class, _Component); function _class() { var _temp, _this, _ret; classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), possibleConstructorReturn(_this, _ret); } _class.prototype.componentWillReceiveProps = function componentWillReceiveProps() { this.cachedHandlers = {}; }; _class.prototype.render = function render() { return factory(_extends({}, this.props, this.handlers)); }; return _class; }(Component), _initialiseProps = function _initialiseProps() { var _this2 = this; this.cachedHandlers = {}; this.handlers = mapValues(typeof handlers === 'function' ? handlers(this.props) : handlers, function (createHandler, handlerName) { return function () { var cachedHandler = _this2.cachedHandlers[handlerName]; if (cachedHandler) { return cachedHandler.apply(undefined, arguments); } var handler = createHandler(_this2.props); _this2.cachedHandlers[handlerName] = handler; if (process.env.NODE_ENV !== 'production' && typeof handler !== 'function') { console.error( // eslint-disable-line no-console 'withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.'); } return handler.apply(undefined, arguments); }; }); }, _temp2; }; }; var withHandlers$1 = createHelper(withHandlers, 'withHandlers'); var defaultProps = function defaultProps(props) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var DefaultProps = function DefaultProps(ownerProps) { return factory(ownerProps); }; DefaultProps.defaultProps = props; return DefaultProps; }; }; var defaultProps$1 = createHelper(defaultProps, 'defaultProps'); var omit = function omit(obj, keys) { var rest = objectWithoutProperties(obj, []); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (rest.hasOwnProperty(key)) { delete rest[key]; } } return rest; }; var renameProp = function renameProp(oldName, newName) { return mapProps$1(function (props) { var _babelHelpers$extends; return _extends({}, omit(props, [oldName]), (_babelHelpers$extends = {}, _babelHelpers$extends[newName] = props[oldName], _babelHelpers$extends)); }); }; var renameProp$1 = createHelper(renameProp, 'renameProp'); var keys = Object.keys; var mapKeys = function mapKeys(obj, func) { return keys(obj).reduce(function (result, key) { var val = obj[key]; /* eslint-disable no-param-reassign */ result[func(val, key)] = val; /* eslint-enable no-param-reassign */ return result; }, {}); }; var renameProps = function renameProps(nameMap) { return mapProps$1(function (props) { return _extends({}, omit(props, keys(nameMap)), mapKeys(pick(props, keys(nameMap)), function (_, oldName) { return nameMap[oldName]; })); }); }; var renameProps$1 = createHelper(renameProps, 'renameProps'); var flattenProp = function flattenProp(propName) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (props) { return factory(_extends({}, props, props[propName])); }; }; }; var flattenProp$1 = createHelper(flattenProp, 'flattenProp'); var withState = function withState(stateName, stateUpdaterName, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState }, _this.updateStateValue = function (updateFn, callback) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn }; }, callback); }, _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[stateUpdaterName] = this.updateStateValue, _babelHelpers$extends))); }; return _class2; }(Component); }; }; var withState$1 = createHelper(withState, 'withState'); var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class2, _Component); function _class2() { var _temp, _this, _ret; classCallCheck(this, _class2); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: _this.initializeStateValue() }, _this.dispatch = function (action) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: reducer(stateValue, action) }; }); }, _temp), possibleConstructorReturn(_this, _ret); } _class2.prototype.initializeStateValue = function initializeStateValue() { if (initialState !== undefined) { return typeof initialState === 'function' ? initialState(this.props) : initialState; } return reducer(undefined, { type: '@@recompose/INIT' }); }; _class2.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[dispatchName] = this.dispatch, _babelHelpers$extends))); }; return _class2; }(Component); }; }; var withReducer$1 = createHelper(withReducer, 'withReducer'); var identity = function identity(Component$$1) { return Component$$1; }; var branch = function branch(test, left) { var right = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : identity; return function (BaseComponent) { var leftFactory = void 0; var rightFactory = void 0; return function (props) { if (test(props)) { leftFactory = leftFactory || createFactory(left(BaseComponent)); return leftFactory(props); } rightFactory = rightFactory || createFactory(right(BaseComponent)); return rightFactory(props); }; }; }; var branch$1 = createHelper(branch, 'branch'); var renderComponent = function renderComponent(Component$$1) { return function (_) { var factory = createFactory(Component$$1); var RenderComponent = function RenderComponent(props) { return factory(props); }; if (process.env.NODE_ENV !== 'production') { RenderComponent.displayName = wrapDisplayName(Component$$1, 'renderComponent'); } return RenderComponent; }; }; var renderComponent$1 = createHelper(renderComponent, 'renderComponent', false); var Nothing = function (_Component) { inherits(Nothing, _Component); function Nothing() { classCallCheck(this, Nothing); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Nothing.prototype.render = function render() { return null; }; return Nothing; }(Component); Nothing.displayName = 'Nothing'; var renderNothing = function renderNothing(_) { return Nothing; }; var renderNothing$1 = createHelper(renderNothing, 'renderNothing', false, true); var shouldUpdate = function shouldUpdate(test) { return function (BaseComponent) { var factory = createFactory(BaseComponent); return function (_Component) { inherits(_class, _Component); function _class() { classCallCheck(this, _class); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } _class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return test(this.props, nextProps); }; _class.prototype.render = function render() { return factory(this.props); }; return _class; }(Component); }; }; var shouldUpdate$1 = createHelper(shouldUpdate, 'shouldUpdate'); var pure = shouldUpdate$1(function (props, nextProps) { return !shallowEqual(props, nextProps); }); var pure$1 = createHelper(pure, 'pure', true, true); var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) { return shouldUpdate$1(function (props, nextProps) { return !shallowEqual(pick(nextProps, propKeys), pick(props, propKeys)); }); }; var onlyUpdateForKeys$1 = createHelper(onlyUpdateForKeys, 'onlyUpdateForKeys'); var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) { var propTypes = BaseComponent.propTypes; if (process.env.NODE_ENV !== 'production') { if (!propTypes) { /* eslint-disable */ console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".')); /* eslint-enable */ } } var propKeys = Object.keys(propTypes || {}); var OnlyUpdateForPropTypes = onlyUpdateForKeys$1(propKeys)(BaseComponent); return OnlyUpdateForPropTypes; }; var onlyUpdateForPropTypes$1 = createHelper(onlyUpdateForPropTypes, 'onlyUpdateForPropTypes', true, true); var withContext = function withContext(childContextTypes, getChildContext) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithContext = function (_Component) { inherits(WithContext, _Component); function WithContext() { var _temp, _this, _ret; classCallCheck(this, WithContext); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.getChildContext = function () { return getChildContext(_this.props); }, _temp), possibleConstructorReturn(_this, _ret); } WithContext.prototype.render = function render() { return factory(this.props); }; return WithContext; }(Component); WithContext.childContextTypes = childContextTypes; return WithContext; }; }; var withContext$1 = createHelper(withContext, 'withContext'); var getContext = function getContext(contextTypes) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var GetContext = function GetContext(ownerProps, context) { return factory(_extends({}, ownerProps, context)); }; GetContext.contextTypes = contextTypes; return GetContext; }; }; var getContext$1 = createHelper(getContext, 'getContext'); var lifecycle = function lifecycle(spec) { return function (BaseComponent) { var factory = createFactory(BaseComponent); if (process.env.NODE_ENV !== 'production' && spec.hasOwnProperty('render')) { console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.'); } return function (_Component) { inherits(_class, _Component); function _class() { classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))); Object.assign(_this, spec); return _this; } _class.prototype.render = function render() { return factory(_extends({}, this.props, this.state)); }; return _class; }(Component); }; }; var lifecycle$1 = createHelper(lifecycle, 'lifecycle'); var toClass = function toClass(baseComponent) { if (isClassComponent(baseComponent)) { return baseComponent; } var ToClass = function (_Component) { inherits(ToClass, _Component); function ToClass() { classCallCheck(this, ToClass); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } ToClass.prototype.render = function render() { if (typeof baseComponent === 'string') { return React.createElement(baseComponent, this.props); } return baseComponent(this.props, this.context); }; return ToClass; }(Component); ToClass.displayName = getDisplayName(baseComponent); ToClass.propTypes = baseComponent.propTypes; ToClass.contextTypes = baseComponent.contextTypes; ToClass.defaultProps = baseComponent.defaultProps; return ToClass; }; var setStatic = function setStatic(key, value) { return function (BaseComponent) { /* eslint-disable no-param-reassign */ BaseComponent[key] = value; /* eslint-enable no-param-reassign */ return BaseComponent; }; }; var setStatic$1 = createHelper(setStatic, 'setStatic', false); var setPropTypes = function setPropTypes(propTypes) { return setStatic$1('propTypes', propTypes); }; var setPropTypes$1 = createHelper(setPropTypes, 'setPropTypes', false); var setDisplayName = function setDisplayName(displayName) { return setStatic$1('displayName', displayName); }; var setDisplayName$1 = createHelper(setDisplayName, 'setDisplayName', false); function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(undefined, arguments)); }; }); } var createEagerElement = function createEagerElement(type, props, children) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); /* eslint-disable */ var hasKey = props && props.hasOwnProperty('key'); /* eslint-enable */ return createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children); }; var createSink = function createSink(callback) { return function (_Component) { inherits(Sink, _Component); function Sink() { classCallCheck(this, Sink); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Sink.prototype.componentWillMount = function componentWillMount() { callback(this.props); }; Sink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { callback(nextProps); }; Sink.prototype.render = function render() { return null; }; return Sink; }(Component); }; var componentFromProp = function componentFromProp(propName) { var Component$$1 = function Component$$1(props) { return createEagerElement(props[propName], omit(props, [propName])); }; Component$$1.displayName = 'componentFromProp(' + propName + ')'; return Component$$1; }; var nest = function nest() { for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) { Components[_key] = arguments[_key]; } var factories = Components.map(createFactory); var Nest = function Nest(_ref) { var props = objectWithoutProperties(_ref, []), children = _ref.children; return factories.reduceRight(function (child, factory) { return factory(props, child); }, children); }; if (process.env.NODE_ENV !== 'production') { var displayNames = Components.map(getDisplayName); Nest.displayName = 'nest(' + displayNames.join(', ') + ')'; } return Nest; }; var hoistStatics = function hoistStatics(higherOrderComponent) { return function (BaseComponent) { var NewComponent = higherOrderComponent(BaseComponent); hoistNonReactStatics(NewComponent, BaseComponent); return NewComponent; }; }; var _config = { fromESObservable: null, toESObservable: null }; var configureObservable = function configureObservable(c) { _config = c; }; var config = { fromESObservable: function fromESObservable(observable) { return typeof _config.fromESObservable === 'function' ? _config.fromESObservable(observable) : observable; }, toESObservable: function toESObservable(stream) { return typeof _config.toESObservable === 'function' ? _config.toESObservable(stream) : stream; } }; var componentFromStreamWithConfig = function componentFromStreamWithConfig(config$$1) { return function (propsToVdom) { return function (_Component) { inherits(ComponentFromStream, _Component); function ComponentFromStream() { var _config$fromESObserva; var _temp, _this, _ret; classCallCheck(this, ComponentFromStream); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { vdom: null }, _this.propsEmitter = createChangeEmitter(), _this.props$ = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = _this.propsEmitter.listen(function (props) { if (props) { observer.next(props); } else { observer.complete(); } }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)), _this.vdom$ = config$$1.toESObservable(propsToVdom(_this.props$)), _temp), possibleConstructorReturn(_this, _ret); } // Stream of props // Stream of vdom ComponentFromStream.prototype.componentWillMount = function componentWillMount() { var _this2 = this; // Subscribe to child prop changes so we know when to re-render this.subscription = this.vdom$.subscribe({ next: function next(vdom) { _this2.setState({ vdom: vdom }); } }); this.propsEmitter.emit(this.props); }; ComponentFromStream.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { // Receive new props from the owner this.propsEmitter.emit(nextProps); }; ComponentFromStream.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return nextState.vdom !== this.state.vdom; }; ComponentFromStream.prototype.componentWillUnmount = function componentWillUnmount() { // Call without arguments to complete stream this.propsEmitter.emit(); // Clean-up subscription before un-mounting this.subscription.unsubscribe(); }; ComponentFromStream.prototype.render = function render() { return this.state.vdom; }; return ComponentFromStream; }(Component); }; }; var componentFromStream = componentFromStreamWithConfig(config); var identity$1 = function identity(t) { return t; }; var componentFromStream$2 = componentFromStreamWithConfig({ fromESObservable: identity$1, toESObservable: identity$1 }); var mapPropsStreamWithConfig = function mapPropsStreamWithConfig(config$$1) { return function (transform) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var fromESObservable = config$$1.fromESObservable, toESObservable = config$$1.toESObservable; return componentFromStream$2(function (props$) { var _ref; return _ref = { subscribe: function subscribe(observer) { var subscription = toESObservable(transform(fromESObservable(props$))).subscribe({ next: function next(childProps) { return observer.next(factory(childProps)); } }); return { unsubscribe: function unsubscribe() { return subscription.unsubscribe(); } }; } }, _ref[$$observable] = function () { return this; }, _ref; }); }; }; }; var mapPropsStream = mapPropsStreamWithConfig(config); var mapPropsStream$1 = createHelper(mapPropsStream, 'mapPropsStream'); var createEventHandlerWithConfig = function createEventHandlerWithConfig(config$$1) { return function () { var _config$fromESObserva; var emitter = createChangeEmitter(); var stream = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = emitter.listen(function (value) { return observer.next(value); }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)); return { handler: emitter.emit, stream: stream }; }; }; var createEventHandler = createEventHandlerWithConfig(config); // Higher-order component helpers // Static property helpers // Composition function // Other utils // Observable helpers export { mapProps$1 as mapProps, withProps$1 as withProps, withPropsOnChange$1 as withPropsOnChange, withHandlers$1 as withHandlers, defaultProps$1 as defaultProps, renameProp$1 as renameProp, renameProps$1 as renameProps, flattenProp$1 as flattenProp, withState$1 as withState, withReducer$1 as withReducer, branch$1 as branch, renderComponent$1 as renderComponent, renderNothing$1 as renderNothing, shouldUpdate$1 as shouldUpdate, pure$1 as pure, onlyUpdateForKeys$1 as onlyUpdateForKeys, onlyUpdateForPropTypes$1 as onlyUpdateForPropTypes, withContext$1 as withContext, getContext$1 as getContext, lifecycle$1 as lifecycle, toClass, setStatic$1 as setStatic, setPropTypes$1 as setPropTypes, setDisplayName$1 as setDisplayName, compose, getDisplayName, wrapDisplayName, shallowEqual, isClassComponent, createEagerElement, createFactory as createEagerFactory, createSink, componentFromProp, nest, hoistStatics, componentFromStream, mapPropsStream$1 as mapPropsStream, createEventHandler, configureObservable as setObservableConfig };
client/modules/User/pages/UserSignUpPage.js
XuHaoJun/tiamat
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { compose } from 'recompose'; import { hot } from 'react-hot-loader'; import Paper from '@material-ui/core/Paper'; import SignUpForm from '../components/SignUpForm'; import { replace } from 'react-router-redux'; import { setHeaderTitle } from '../../MyApp/MyAppActions'; import { getIsLoggedIn } from '../UserReducer'; const styles = { paper: { textAlign: 'center', verticalAlign: 'middle', width: 500, margin: 'auto', }, form: { padding: 15, }, signUpFormWithMedium: { display: 'flex', alignItems: 'center', justifyContent: 'center', }, }; class UserSignUpPage extends Component { static propTypes = { isLoggedIn: PropTypes.bool.isRequired, }; static getInitialAction() { return setHeaderTitle('註冊'); } componentWillMount() { this.props.dispatch(setHeaderTitle('註冊')); } componentDidMount() { this.goBackIfLoggedIn(); } componentDidUpdate() { this.goBackIfLoggedIn(); } goBackIfLoggedIn = () => { const { isLoggedIn } = this.props; if (isLoggedIn) { const from = this.props.location.query.from || '/'; this.props.dispatch(replace(from)); } }; renderDesktop = () => { return ( <Paper style={styles.paper}> <SignUpForm style={styles.form} /> </Paper> ); }; renderMobile = () => { return <SignUpForm style={styles.signUpFormWithMedium} />; }; render() { const meta = [ { name: 'description', content: '註冊', }, ]; const content = this.props.browser.lessThan.medium ? this.renderMobile() : this.renderDesktop(); return ( <React.Fragment> <Helmet title="註冊" meta={meta} /> <React.Fragment>{content}</React.Fragment> </React.Fragment> ); } } function mapStateToProps(state) { const { browser } = state; return { browser, isLoggedIn: getIsLoggedIn(state), }; } export default compose( hot(module), connect(mapStateToProps) )(UserSignUpPage);
src/components/ResultLoggerView.js
IUnknown68/karma-live-reporter
//============================================================================== import React, { Component } from 'react'; import attachListener from 'attachListener'; import autoScroll from 'autoScroll'; import { SPEC_COMPLETED, BROWSER_START } from 'messages'; //============================================================================== export default class ResultLoggerView extends Component { static listener = { [BROWSER_START]: function(browser) { if (browser.id === this.props.browser.id) { this.clear(); } }, [SPEC_COMPLETED]: function(browser, result) { if (browser.id === this.props.browser.id) { this.appendLog(result, true); } } }; //---------------------------------------------------------------------------- constructor(props) { super(props); autoScroll(this); attachListener(this); } //---------------------------------------------------------------------------- componentDidMount() { this.renderAllEntries(); } //---------------------------------------------------------------------------- shouldComponentUpdate(nextProps, nextState) { return false; } //---------------------------------------------------------------------------- clear() { let node = this.refs.root; while (node.firstChild) { node.removeChild(node.firstChild); } } //---------------------------------------------------------------------------- renderAllEntries() { this.currentSuite = []; this.props.entries.forEach(entry => { this.appendLog(entry, false); }); setTimeout(this.updateScroll, 10); } //---------------------------------------------------------------------------- appendLog(entry, update = false) { const entryNode = document.createElement('div'); const suite = entry.suite; let suiteChanged = false; for (let n = 0; n < suite.length; n++) { suiteChanged |= (this.currentSuite[n] !== suite[n]); if (suiteChanged) { const node = document.createElement('div'); node.style.marginLeft = `${n}em`; entryNode.appendChild(node) .appendChild(document.createTextNode(suite[n])); } } this.currentSuite = suite; this.appendLogEntry(entry, entryNode); this.refs.root.appendChild(entryNode); if (update) { this.updateScroll(); } } //---------------------------------------------------------------------------- appendLogEntry(entry, entryNode) { const node = document.createElement('div'); const className = (entry.skipped) ? 'skipped' : (entry.success) ? 'succeeded' : 'failed'; node.className = `description ${className}`; const indent = entry.suite.length; node.style.marginLeft = `${indent}em`; this.appendLogEntryIcon(className, node); node.appendChild(document.createTextNode(entry.description)); this.appendLogEntryLog(entry, node); entryNode.appendChild(node); } //---------------------------------------------------------------------------- appendLogEntryIcon(className, parentNode) { let iconClassName = 'glyphicon glyphicon-'; switch(className) { case 'skipped': iconClassName += 'minus'; break; case 'succeeded': iconClassName += 'ok'; break; case 'failed': iconClassName += 'remove'; break; } if (iconClassName) { parentNode.appendChild(document.createElement('span')) .className = iconClassName; } } //---------------------------------------------------------------------------- appendLogEntryLog(entry, parentNode) { if (!entry.log) { return; } entry.log.forEach(logEntry => { const el = document.createElement('div'); el.appendChild(document.createTextNode(logEntry)); parentNode.appendChild(el) .className = 'indent'; }); } //---------------------------------------------------------------------------- render() { return ( <div ref="root" className="logger results" /> ); } }
examples/js/column-filter/select-filter.js
powerhome/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const qualityType = { 0: 'good', 1: 'Bad', 2: 'unknown' }; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, quality: i % 3 }); } } addProducts(5); function enumFormatter(cell, row, enumObject) { return enumObject[cell]; } export default class SelectFilter extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='quality' filterFormatted dataFormat={ enumFormatter } formatExtraData={ qualityType } filter={ { type: 'SelectFilter', options: qualityType } }>Product Quality</TableHeaderColumn> </BootstrapTable> ); } }
apps/marketplace/components/Brief/Edit/AddSellerListItems.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import PropTypes from 'prop-types' const AddSellerListItems = props => { const { onSellerClick, sellers } = props return sellers.map(seller => ( <li key={seller.code}> <a href={`#${seller.code}`} onClick={e => { e.preventDefault() onSellerClick(seller.code, seller.name) }} > {seller.name} </a> </li> )) } AddSellerListItems.defaultProps = { onSellerClick: () => {}, sellers: [] } AddSellerListItems.propTypes = { onSellerClick: PropTypes.func.isRequired, sellers: PropTypes.arrayOf( PropTypes.shape({ code: PropTypes.number.isRequired, name: PropTypes.string.isRequired }) ).isRequired } export default AddSellerListItems
fields/types/azurefile/AzureFileColumn.js
ligson/keystone
import React from 'react'; var AzureFileColumn = React.createClass({ renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; return <a href={value.url} target='_blank'>{value.url}</a>; }, render () { return ( <td className="ItemList__col"> <div className="ItemList__value ItemList__value--azure-file">{this.renderValue()}</div> </td> ); } }); module.exports = AzureFileColumn;
src/svg-icons/maps/directions-walk.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsWalk = (props) => ( <SvgIcon {...props}> <path d="M13.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9L7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1L6 8.3V13h2V9.6l1.8-.7"/> </SvgIcon> ); MapsDirectionsWalk = pure(MapsDirectionsWalk); MapsDirectionsWalk.displayName = 'MapsDirectionsWalk'; MapsDirectionsWalk.muiName = 'SvgIcon'; export default MapsDirectionsWalk;
example/src/components/SpacedSpan.js
ethanselzer/react-image-magnify
import React from 'react'; export default function SpacedSpan({ className, children }) { return ( <span className={className}> {' '}{children}{' '} </span> ); }
admin/client/App/screens/Home/index.js
brianjd/keystone
/** * The Home view is the view one sees at /keystone. It shows a list of all lists, * grouped by their section. */ import React from 'react'; import { Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import Lists from './components/Lists'; import Section from './components/Section'; import AlertMessages from '../../shared/AlertMessages'; import { loadCounts, } from './actions'; var HomeView = React.createClass({ displayName: 'HomeView', getInitialState () { return { modalIsOpen: true, }; }, // When everything is rendered, start loading the item counts of the lists // from the API componentDidMount () { this.props.dispatch(loadCounts()); }, getSpinner () { if (this.props.counts && Object.keys(this.props.counts).length === 0 && (this.props.error || this.props.loading)) { return ( <Spinner /> ); } return null; }, render () { const spinner = this.getSpinner(); return ( <Container data-screen-id="home"> <div className="dashboard-header"> <div className="dashboard-heading">{Keystone.brand}</div> </div> <div className="dashboard-groups"> {(this.props.error) && ( <AlertMessages alerts={{ error: { error: "There is a problem with the network, we're trying to reconnect...", } }} /> )} {/* Render flat nav */} {Keystone.nav.flat ? ( <Lists counts={this.props.counts} lists={Keystone.lists} spinner={spinner} /> ) : ( <div> {/* Render nav with sections */} {Keystone.nav.sections.map((navSection) => { return ( <Section key={navSection.key} id={navSection.key} label={navSection.label}> <Lists counts={this.props.counts} lists={navSection.lists} spinner={spinner} /> </Section> ); })} {/* Render orphaned lists */} {Keystone.orphanedLists.length ? ( <Section label="Other" icon="octicon-database"> <Lists counts={this.props.counts} lists={Keystone.orphanedLists} spinner={spinner} /> </Section> ) : null} </div> )} </div> </Container> ); }, }); export { HomeView, }; export default connect((state) => ({ counts: state.home.counts, loading: state.home.loading, error: state.home.error, }))(HomeView);
index.android.js
Hey2Li/RNGD
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import Main from './app/main/GDMain' export default class RNGD extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> <Main/> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('RNGD', () => RNGD);
components/index_section_02.js
MonkingStand/MS-blog-site-v3.0
import React from 'react'; class IndexSection02 extends React.Component { render() { const css_tag_p = { marginBottom: 20, fontWeight : 300, textAlign : 'center' }; return ( <section id="main_content"> <p style = { css_tag_p }> code less,do more </p> </section> ); }; }; export default IndexSection02;
docs/src/app/components/pages/components/FlatButton/ExampleComplex.js
pomerantsev/material-ui
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import ActionAndroid from 'material-ui/svg-icons/action/android'; const styles = { exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const FlatButtonExampleComplex = () => ( <div> <FlatButton label="Choose an Image" labelPosition="before"> <input type="file" style={styles.exampleImageInput} /> </FlatButton> <FlatButton label="Label before" labelPosition="before" primary={true} style={styles.button} icon={<ActionAndroid />} /> <FlatButton label="GitHub Link" href="https://github.com/callemall/material-ui" secondary={true} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default FlatButtonExampleComplex;
src/js/tabscontrolled/index.js
HBM/md-components
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' class TabsControlled extends React.PureComponent { static propTypes = { tabs: PropTypes.array } static defaultProps = { tabs: [ 'germany', 'spain', 'sweden' ] } state = { direction: '' } componentWillReceiveProps (nextProps) { const direction = nextProps.index > this.props.index ? 'right' : 'left' this.setState({ direction }) } onClick = (event, index) => { event.preventDefault() this.props.onChange(index) } render () { const width = 100 / this.props.tabs.length const left = this.props.index * width const right = (this.props.tabs.length - this.props.index - 1) * width return ( <div className='mdc-TabsControlled'> {this.props.tabs.map((tab, index) => ( <a key={tab} onClick={event => this.onClick(event, index)} className={classnames('mdc-TabsControlled-item', { 'is-active': this.props.index === index })} href='' > {tab} </a> ))} {this.props.index === -1 ? null : ( <div className={`mdc-Tabs-InkBar transition-${this.state.direction}`} style={{ left: `${left}%`, right: `${right}%` }} /> )} </div> ) } } export default TabsControlled
src/js/components/icons/base/PlatformUnixware.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-platform-unixware`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-unixware'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M11.1202881,4.92721589 L19.7127168,8.40180443 L19.7127168,4.92721589 L11.1202881,4.92721589 Z M5,4.92721589 L5,24 L8.13126023,24 L5.68766714,21.7034393 L15.7579991,10.8346606 L8.99134942,8.09586582 L10.2724516,4.92721589 L5,4.92721589 Z M9.27644581,24 L19.7127168,24 L19.7127168,12.6521027 L9.27644581,24 Z M17.6912987,2.17525891 C17.5552558,2.17525891 17.4922239,2.37433375 17.4922239,2.76212546 L17.9008578,2.76212546 C17.9008578,2.36397579 17.8379522,2.17525891 17.6912987,2.17525891 M14.9250301,3.47443696 C14.9250301,3.61073248 14.9986726,3.70483829 15.1032627,3.70483829 C15.1974948,3.70483829 15.2919796,3.62096412 15.3546326,3.46395269 L15.3546326,2.92976012 C15.0509677,3.1077401 14.9250301,3.28584639 14.9250301,3.47443696 M17.8694177,3.71547414 C18.0054606,3.71547414 18.1209139,3.64208424 18.2256303,3.50591503 L18.2256303,3.87261189 C18.0893347,3.99842315 17.9530392,4.05071819 17.7959014,4.05071819 C17.3875201,4.05071819 17.1360239,3.68402133 17.1360239,2.95062761 C17.1360239,2.26952893 17.3454567,1.85053703 17.7122799,1.85053703 C17.9324496,1.85053703 18.0577556,1.99706419 18.1417561,2.16481253 C18.2045354,2.26952893 18.2675673,2.53150939 18.2675673,3.03437546 L17.5027208,3.03437546 C17.5027208,3.47446222 17.6284057,3.71547414 17.8694177,3.71547414 L17.8694177,3.71547414 Z M17.0415392,2.3113397 C16.9889915,2.28026583 16.9474334,2.25904466 16.8844014,2.25904466 C16.6013261,2.25904466 16.4862518,2.92965907 16.4862518,3.1707973 L16.4862518,3.99842315 L16.1195549,3.99842315 L16.1195549,1.91331634 L16.4862518,1.91331634 L16.4862518,2.47934067 L16.496736,2.47934067 C16.6433895,1.97634828 16.7166531,1.88186353 16.8844014,1.88186353 C16.957665,1.88186353 17.0102127,1.89247411 17.072992,1.93428488 L17.0415392,2.3113397 Z M15.9309643,3.89358044 C15.7947951,4.00903374 15.7214052,4.05071819 15.6375311,4.05071819 C15.5119724,4.05071819 15.4177403,3.95635975 15.3756769,3.77812714 C15.239634,3.96684402 15.1033385,4.05071819 14.9671693,4.05071819 C14.7469996,4.05071819 14.5582827,3.80957995 14.5582827,3.52688358 C14.5582827,3.18115526 14.7783261,3.01340692 15.3547084,2.67803656 L15.3547084,2.47934067 C15.3547084,2.29037115 15.2920554,2.20674962 15.1347913,2.20674962 C14.9878852,2.20674962 14.8308738,2.30085543 14.6109567,2.55247794 L14.6109567,2.12300176 C14.8308738,1.92380061 14.9671693,1.85053703 15.1661178,1.85053703 C15.4387089,1.85053703 15.7214052,2.02864332 15.7214052,2.41630873 L15.7214052,3.60002084 C15.7214052,3.6945056 15.7423738,3.71547414 15.7843109,3.71547414 C15.8052794,3.71547414 15.8575744,3.68402133 15.9309643,3.61075775 L15.9309643,3.89358044 Z M13.6680039,4.04023392 L13.2382751,1.93428488 L13.2277908,1.93428488 L12.8191568,4.04023392 L12.5362078,4.04023392 L11.8763303,0.855036529 L12.2954486,0.855036529 L12.6621454,2.97159615 L12.6722507,2.97159615 L13.0914953,0.855036529 L13.3850549,0.855036529 L13.7936888,3.01340692 L14.1915858,0.855036529 L14.6213146,0.855036529 L13.9403423,4.04023392 L13.6680039,4.04023392 Z M11.4570858,3.99842315 L11.1428103,3.27538738 L10.8601139,3.99842315 L10.4720696,3.99842315 L10.9542197,2.92965907 L10.4720696,1.91331634 L10.8601139,1.91331634 L11.1428103,2.57344648 L11.4151487,1.91331634 L11.7924562,1.91331634 L11.3420115,2.92965907 L11.8448775,3.99842315 L11.4570858,3.99842315 Z M10.0846568,1.23234398 C9.95884555,1.23234398 9.86473974,1.13798554 9.86473974,1.02278487 C9.86473974,0.897099931 9.95884555,0.80274149 10.0846568,0.80274149 C10.1997312,0.80274149 10.2940896,0.897099931 10.2940896,1.02278487 C10.2940896,1.13798554 10.1997312,1.23234398 10.0846568,1.23234398 L10.0846568,1.23234398 Z M9.89606624,3.99842315 L10.2625105,3.99842315 L10.2625105,1.91319002 L9.89606624,1.91319002 L9.89606624,3.99842315 Z M9.53997997,3.99842315 L9.17315679,3.99842315 L9.17315679,2.49993026 C9.17315679,2.3220766 9.12060912,2.20674962 8.97395564,2.20674962 C8.85875497,2.20674962 8.7748808,2.29037115 8.69125927,2.45811949 L8.69125927,3.99842315 L8.32443609,3.99842315 L8.32443609,1.91331634 L8.69125927,1.91331634 L8.69125927,2.13335972 L8.70174354,2.13335972 C8.80633362,1.95525343 8.92178692,1.88186353 9.07867203,1.88186353 C9.34077882,1.88186353 9.53997997,2.08106468 9.53997997,2.49993026 L9.53997997,3.99842315 Z M7.92628642,3.19176585 C7.92628642,3.87261189 7.47571539,4.04023392 7.22447183,4.04023392 C6.83668011,4.04023392 6.52215197,3.72595841 6.52215197,3.22309234 L6.52215197,0.855036529 L6.93078592,0.855036529 L6.93078592,3.22309234 C6.93078592,3.48494649 7.02527067,3.6631791 7.22447183,3.6631791 C7.38160958,3.6631791 7.51765247,3.53749416 7.51765247,3.23357662 L7.51765247,0.855036529 L7.92628642,0.855036529 L7.92628642,3.19176585 Z M5.00003789,4.92722853 L19.7127547,4.92722853 L19.7127547,0 L5.00003789,0 L5.00003789,4.92722853 Z" opacity=".8"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformUnixware'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
lib/editor/components/editors/LogicalVariableForm.js
jirokun/survey-designer-js
/* eslint-env browser */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Panel, Button, Glyphicon, Form, Col, FormControl } from 'react-bootstrap'; import classNames from 'classnames'; import { List } from 'immutable'; import * as EditorActions from '../../actions'; class LogicalVariableForm extends Component { /** logicalVariableからstateを生成する */ static generateState(logicalVariable) { return { editMode: false, variableName: logicalVariable.getVariableName(), operands: logicalVariable.getOperands(), operators: logicalVariable.getOperators(), errorMessage: null, }; } constructor(props) { super(props); const { logicalVariable } = props; this.state = LogicalVariableForm.generateState(logicalVariable); } /** editModeの変更 */ handleSubmit(e) { e.preventDefault(); this.handleClickSave(); } /** editModeの変更 */ handleChangeEditMode(editMode) { this.setState({ editMode }); } /** LogicalVariableの変更 */ handleRemoveLogicalVariable() { const { page, logicalVariable, removeLogicalVariable } = this.props; removeLogicalVariable(page.getId(), logicalVariable.getId()); } /** LogicalVariableの変更 */ handleClickCancel() { const { logicalVariable } = this.props; this.setState(LogicalVariableForm.generateState(logicalVariable)); } /** LogicalVariableの変更 */ handleClickSave() { const { logicalVariable, page, changeLogicalVariable } = this.props; const variableName = this.state.variableName; if (!page.isUniqueLogicalVariableName(logicalVariable.getId(), variableName)) { this.setState({ errorMessage: 'ラベルが重複しています' }); return; } const invalidChars = [ { char: ' ', desc: '半角スペース' }, { char: '#', desc: '半角シャープ' }, { char: '{', desc: '半角左ブレース' }, { char: '}', desc: '半角右ブレース' }, ]; for (let i = 0; i < invalidChars.length; i++) { if (variableName.indexOf(invalidChars[i].char) !== -1) { this.setState({ errorMessage: `ラベルに使用できない文字が含まれています。<br />使用できない文字<br />${invalidChars.map(c => `'${c.char}':${c.desc}`).join('<br />')}` }); return; } } const newLogicalVariable = logicalVariable .set('variableName', this.state.variableName) .set('operands', this.state.operands) .set('operators', this.state.operators); changeLogicalVariable(page.getId(), newLogicalVariable.getId(), newLogicalVariable); this.setState({ editMode: false, errorMessage: null }); } /** 名前の変更 */ handleChangeName(variableName) { this.setState({ variableName }); } /** オペランドの追加*/ handleAddOperand(index) { const { operands, operators } = this.state; this.setState({ operands: operands.insert(index + 1, ''), operators: operators.insert(index, ''), }); } /** オペランドの削除 */ handleRemoveOperand(index) { const { operands, operators } = this.state; this.setState({ operands: operands.delete(index), operators: operators.delete(index - 1), }); } /** 式が変更されたときのハンドラ */ handleChangeExpression() { const operands = List(Array.prototype.slice.call(this.rootEl.getElementsByClassName('operand')).map(el => el.value)); const operators = List(Array.prototype.slice.call(this.rootEl.getElementsByClassName('operator')).map(el => el.value)); this.setState({ operands, operators, }); } /** 計算式部分を作成する */ createExpression(editMode, operand, operator, precedingOutputDefinitions, index) { const { logicalVariable } = this.props; const { operators } = this.state; const key = `LogicalVariableForm_${logicalVariable.getId()}_${index}`; return ( <div key={key} className="expression"> <FormControl className="operand" componentClass="select" disabled={!editMode} value={operand} onChange={() => this.handleChangeExpression()}> <option value="" /> {this.createOutputDefinitionOptions(precedingOutputDefinitions, index)} </FormControl> <Glyphicon className={classNames('clickable icon-button text-info', { invisible: !editMode })} glyph="plus-sign" onClick={() => this.handleAddOperand(index)} /> <Glyphicon className={classNames('clickable icon-button text-danger', { invisible: !editMode || index === 0 || operators.size === 1 })} glyph="remove-sign" onClick={() => this.handleRemoveOperand(index)} /> { operator !== undefined ? ( <FormControl className="operator" componentClass="select" disabled={!editMode} value={operator} onChange={() => this.handleChangeExpression()}> <option value="" /> <option value="+">+</option> <option value="-">−</option> </FormControl> ) : null } </div> ); } /** outputdefinitionのoptionを作成する */ createOutputDefinitionOptions(precedingOutputDefinitions, index) { const { logicalVariable } = this.props; return precedingOutputDefinitions.map((od, i) => { const key = `LogicalVariableForm_${logicalVariable.getId()}_${index}_${i}`; return <option key={key} value={od.getId()}>{od.getLabelWithOutputNo()}</option>; }); } /** パネルのヘッダーを作成する */ createPanelHeader(variableName) { const { survey, page } = this.props; const name = `${survey.calcPageNo(page.getId())}-L-${variableName}`; return ( <div> {name} <i className={classNames('fa fa-trash pull-right text-danger delete-button', { invisible: page.isEditDisabled() })} onClick={e => this.handleRemoveLogicalVariable(e)} /> </div> ); } render() { const { runtime, survey, page, logicalVariable } = this.props; const { editMode, variableName, operands, operators, errorMessage } = this.state; const precedingOutputDefinitions = survey.findPrecedingOutputDefinition(runtime.findCurrentNode(survey).getId(), true, false) .filter(od => od.getOutputType() === 'number') // numberのものに限る .filter(od => od.getName() !== logicalVariable.getId()); // 自分自身は除く return ( <div ref={(el) => { this.rootEl = el || this.rootEl; }}> <Panel header={this.createPanelHeader(variableName)}> <Form onSubmit={e => this.handleSubmit(e)}> <div> <Col md={3}>ラベル</Col> <Col md={9}>定義</Col> </div> <div> <Col md={3}> <FormControl type="text" value={variableName} disabled={!editMode} onChange={e => this.handleChangeName(e.target.value)} /> </Col> <Col md={9}> {operands.map((operand, i) => this.createExpression(editMode, operand, operators.get(i), precedingOutputDefinitions, i))} </Col> </div> <div> <Col md={12}> <Button disabled={page.isEditDisabled()} className={classNames('pull-right', { hidden: editMode })} bsStyle="default" onClick={() => this.handleChangeEditMode(true)}>編集</Button> <Button className={classNames('pull-right', { hidden: !editMode })} bsStyle="primary" onClick={() => this.handleClickSave(false)}>保存</Button> <Button className={classNames('pull-right', { hidden: !editMode })} onClick={() => this.handleClickCancel(false)}>キャンセル</Button> <span className="pull-right text-danger form-control-static" dangerouslySetInnerHTML={{ __html: errorMessage }} /> </Col> </div> </Form> </Panel> </div> ); } } const stateToProps = state => ({ survey: state.getSurvey(), runtime: state.getRuntime(), view: state.getViewSetting(), }); const actionsToProps = dispatch => ({ changeLogicalVariable: (pageId, logicalVariableId, logicalVariable) => dispatch(EditorActions.changeLogicalVariable(pageId, logicalVariableId, logicalVariable)), removeLogicalVariable: (pageId, logicalVariableId) => dispatch(EditorActions.removeLogicalVariable(pageId, logicalVariableId)), }); export default connect( stateToProps, actionsToProps, )(LogicalVariableForm);
src/components/GuestsTable/GuestsTable.js
joyvuu-dave/comeals-ui-react
// rendered by Guests import React from 'react' import classes from './GuestsTable.scss' // Schema import type { GuestsSchema } from '../../redux/modules/Guests' import type { ResidentsSchema } from '../../redux/modules/Residents' type Props = { ui: { veg_checkbox_disabled: boolean, remove_button_disabled: boolean }, actions: { remove: Function, toggleVeg: Function }, guests: GuestsSchema, residents: ResidentsSchema }; export class GuestsTable extends React.Component<void, Props, void> { constructor () { super() this.handleToggleVeg = this.handleToggleVeg.bind(this) this.handleGuestRemove = this.handleGuestRemove.bind(this) } handleToggleVeg (e) { this.props.actions.toggleVeg({cid: e.target.value}) } handleGuestRemove (e) { this.props.actions.remove({cid: e.target.value}) } renderHost (id) { return this.props.residents.find((resident) => { return resident.id === id }).name } renderCategory (val) { if (val === 1) { return 'Child' } else { return 'Adult' } } renderGuests () { return this.props.guests.map((g) => <tr key={g.cid} className={classes.guest}> <td>{this.renderHost(g.resident_id)}</td> <td>{this.renderCategory(g.multiplier)}</td> <td> <input value={g.cid} disabled={this.props.ui.veg_checkbox_disabled} type='checkbox' checked={g.vegetarian} onChange={this.handleToggleVeg} /> </td> <td> <button value={g.cid} disabled={this.props.ui.remove_button_disabled} type='button' onClick={this.handleGuestRemove}>- Guest</button> </td> </tr> ) } render () { return ( <table className={classes['guests-table']}> <thead> <tr> <th>Host</th> <th>Category</th> <th>Vegetarian</th> <th></th> </tr> </thead> <tbody> {this.renderGuests()} </tbody> </table> ) } } export default GuestsTable
app/components/ShopPage/ShopPage.js
tenhaus/bbwelding
import React from 'react'; import Radium from 'radium'; import _ from 'lodash'; import RetinaImage from 'react-retina-image'; import isRetina from 'is-retina'; import Style from './_ShopPage.style.js'; import Page from '../Page/Page'; import ContentfulEntryStore from '../../stores/ContentfulEntryStore'; import ShopListItemRenderer from '../ShopListItemRenderer/ShopListItemRenderer'; import AltActions from '../../actions/AltActions'; var Markdown = require( "markdown" ).markdown; class ShopPage extends React.Component { constructor() { super(); this.onChange = this.onChange.bind(this); this.onMouseOver = this.onMouseOver.bind(this); this.onMouseOut = this.onMouseOut.bind(this); this.renderMobileListItems = this.renderMobileListItems.bind(this); this.onMobileShopItemChanged = this.onMobileShopItemChanged.bind(this); this.state = { entryStore: ContentfulEntryStore.getState(), showSecondary: false }; } onMouseOver() { this.setState({showSecondary: true}); } onMouseOut() { this.setState({showSecondary: false}); } componentDidMount() { ContentfulEntryStore.listen(this.onChange); } componentWillUnmount() { ContentfulEntryStore.unlisten(this.onChange); } onChange(entryStore) { this.setState({ entryStore: entryStore }); } onMobileShopItemChanged(event) { var name = event.target.value; var item = _.findWhere(this.state.entryStore.shop, {fields: {name: name}}); AltActions.setSelectedShopItem(item); } renderListItems() { return _.map(this.state.entryStore.shop, item => { return <ShopListItemRenderer key={item.fields.name} item={item} />; }); } renderMobileListItems() { var self = this; var selectedShopItemName = self.state.entryStore.selectedShopItem.fields.name; return _.map(this.state.entryStore.shop, item => { let option = ( <option key={item.fields.name} value={item.fields.name}> {item.fields.name} </option> ); if(selectedShopItemName === item.fields.name) { option = ( <option selected key={item.fields.name} value={item.fields.name}> {item.fields.name} </option> ); } return option; }); } render() { let listItems = this.renderListItems(); let mobileListItems = this.renderMobileListItems(); let item = this.state.entryStore.selectedShopItem; let html = Markdown.toHTML(item.fields.name); let profileImage = null; if(item.fields.primaryImage) { profileImage = item.fields.primaryImage.fields.file.url; profileImage += '?w=600&fm=jpg&q=75'; } if(this.state.showSecondary && item.fields.secondaryImage) { profileImage = item.fields.secondaryImage.fields.file.url; profileImage += '?w=600&fm=jpg&q=75'; } return ( <Page title='Our Shop'> <div style={Style.topSection} key='top'> <p>Bluebeam, SDS/2, Fabsuite and P2 systems, Infosight Corp, Shop Data, and Peddinghaus equipment are all part of what makes our jobs run smoothly through the shop.</p> </div> <div style={Style.split} key='split'> <div className='shopItem' style={Style.profile} key='profile'> <select style={Style.mobileTeamList} key='mobile-nav' onChange={this.onMobileShopItemChanged}> {mobileListItems} </select> {/* Profile */} <div onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}> <img src={profileImage} style={Style.profileImage} /> <div dangerouslySetInnerHTML={{__html:html}}></div> </div> </div> {/* Shop list */} <div className='team'> <ul style={Style.teamList}> {listItems} </ul> </div> </div> </Page> ); } } export default Radium(ShopPage);
imports/ui/pages/ResetPassword/ResetPassword.js
lazygalaxy/lazybat-seed-meteorjs
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, Alert, FormGroup, ControlLabel, Button } from 'react-bootstrap'; import { Accounts } from 'meteor/accounts-base'; import { Bert } from 'meteor/themeteorchef:bert'; import validate from '../../../modules/validate'; class ResetPassword extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount() { const component = this; validate(component.form, { rules: { newPassword: { required: true, minlength: 6, }, repeatNewPassword: { required: true, minlength: 6, equalTo: '[name="newPassword"]', }, }, messages: { newPassword: { required: 'Enter a new password, please.', minlength: 'Use at least six characters, please.', }, repeatNewPassword: { required: 'Repeat your new password, please.', equalTo: 'Hmm, your passwords don\'t match. Try again?', }, }, submitHandler() { component.handleSubmit(); }, }); } handleSubmit() { const { match, history } = this.props; const token = match.params.token; Accounts.resetPassword(token, this.newPassword.value, (error) => { if (error) { Bert.alert(error.reason, 'danger'); } else { history.push('/documents'); } }); } render() { return (<div className="ResetPassword"> <Row> <Col xs={12} sm={6} md={4}> <h4 className="page-header">Reset Password</h4> <Alert bsStyle="info"> To reset your password, enter a new one below. You will be logged in with your new password. </Alert> <form ref={form => (this.form = form)} onSubmit={event => event.preventDefault()}> <FormGroup> <ControlLabel>New Password</ControlLabel> <input type="password" className="form-control" ref={newPassword => (this.newPassword = newPassword)} name="newPassword" placeholder="New Password" /> </FormGroup> <FormGroup> <ControlLabel>Repeat New Password</ControlLabel> <input type="password" className="form-control" ref={repeatNewPassword => (this.repeatNewPassword = repeatNewPassword)} name="repeatNewPassword" placeholder="Repeat New Password" /> </FormGroup> <Button type="submit" bsStyle="success">Reset Password &amp; Login</Button> </form> </Col> </Row> </div>); } } ResetPassword.propTypes = { match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, }; export default ResetPassword;
app/src/GenericTable.js
CovertIII/hledger-node-server
import React from 'react'; import R from 'ramda'; const defaultArray = []; const thStyle = { 'textAlign': 'left', 'verticalAlign': 'bottom', 'padding': '8px 8px 8px 0px', 'borderBottomStyle': 'solid', 'borderBottomWidth': '2px', 'borderColor': 'inherit' }; const Header = ({header = defaultArray}) => ( <thead> <tr> { header.map( h => <th style={thStyle}>{ h }</th> ) } </tr> </thead> ); const tdStyle = { 'textAlign': 'left', 'verticalAlign': 'bottom', 'padding': '8px 8px 8px 0px', 'borderColor': 'inherit' }; const Body = ({data = defaultArray}) => ( <tbody> { data.map( (d = defaultArray) => ( <tr> { d.map( (h, i) => <td style={tdStyle}>{ h }</td> )} </tr> ))} </tbody> ) const tableStyle = { fontSize: '14px', lineHeight: '1.25', borderCollapse: 'separate', borderSpacing: '0px', width: '100%' }; export const GenericTable = ({data = defaultArray}) => ( <table style={tableStyle}> <Header header={R.head(data)}/> <Body data={R.tail(data)}/> </table> );
app/components/navigation/personality/PersonalityLinks.js
VasilyShelkov/Vasily
import React, { Component } from 'react'; import Letter from './Letter'; class PersonalityLinks extends Component { render() { var openCB='{'; var closedCB = '}'; var personalities = ['Developer,','Explorer, ','Early-Adopter, ','Anime-Lover'].map((personality, index) => { var personalityLetters = personality.split('').map((letter, index) => { return ( <Letter letter={letter} key={index}/> ); }); var noComma = personality.replace(',', ''); return ( <a key={index} href={`#profile/${noComma}`}> {personalityLetters} </a> ); }); return ( <div id="personalities" className="flow-text col-xs-10 center-align valign"> {openCB} {personalities} {closedCB} </div> ); } } export default PersonalityLinks;
app/javascript/mastodon/features/ui/components/tabs_bar.js
h3zjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { NavLink, withRouter } from 'react-router-dom'; import { FormattedMessage, injectIntl } from 'react-intl'; import { debounce } from 'lodash'; import { isUserTouching } from '../../../is_mobile'; import Icon from 'mastodon/components/icon'; import NotificationsCounterIcon from './notifications_counter_icon'; export const links = [ <NavLink className='tabs-bar__link' to='/timelines/home' data-preview-title-id='column.home' data-preview-icon='home' ><Icon id='home' fixedWidth /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink>, <NavLink className='tabs-bar__link' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><NotificationsCounterIcon /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink>, <NavLink className='tabs-bar__link' exact to='/timelines/public' data-preview-title-id='column.public' data-preview-icon='globe' ><Icon id='globe' fixedWidth /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink>, <NavLink className='tabs-bar__link optional' to='/search' data-preview-title-id='tabs_bar.search' data-preview-icon='bell' ><Icon id='search' fixedWidth /><FormattedMessage id='tabs_bar.search' defaultMessage='Search' /></NavLink>, <NavLink className='tabs-bar__link' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started' data-preview-title-id='getting_started.heading' data-preview-icon='bars' ><Icon id='bars' fixedWidth /></NavLink>, ]; export function getIndex (path) { return links.findIndex(link => link.props.to === path); } export function getLink (index) { return links[index].props.to; } export default @injectIntl @withRouter class TabsBar extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, history: PropTypes.object.isRequired, } setRef = ref => { this.node = ref; } handleClick = (e) => { // Only apply optimization for touch devices, which we assume are slower // We thus avoid the 250ms delay for non-touch devices and the lag for touch devices if (isUserTouching()) { e.preventDefault(); e.persist(); requestAnimationFrame(() => { const tabs = Array(...this.node.querySelectorAll('.tabs-bar__link')); const currentTab = tabs.find(tab => tab.classList.contains('active')); const nextTab = tabs.find(tab => tab.contains(e.target)); const { props: { to } } = links[Array(...this.node.childNodes).indexOf(nextTab)]; if (currentTab !== nextTab) { if (currentTab) { currentTab.classList.remove('active'); } const listener = debounce(() => { nextTab.removeEventListener('transitionend', listener); this.props.history.push(to); }, 50); nextTab.addEventListener('transitionend', listener); nextTab.classList.add('active'); } }); } } render () { const { intl: { formatMessage } } = this.props; return ( <div className='tabs-bar__wrapper'> <nav className='tabs-bar' ref={this.setRef}> {links.map(link => React.cloneElement(link, { key: link.props.to, onClick: this.handleClick, 'aria-label': formatMessage({ id: link.props['data-preview-title-id'] }) }))} </nav> <div id='tabs-bar__portal' /> </div> ); } }
service/client/src/index.js
lwoites/unq-cloudsystems
import Application from './Application'; import './index.css'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <Application></Application>, document.getElementById('root') );
packages/material-ui-icons/src/VideogameAsset.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let VideogameAsset = 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>; VideogameAsset = pure(VideogameAsset); VideogameAsset.muiName = 'SvgIcon'; export default VideogameAsset;
docs/app/Examples/modules/Search/index.js
vageeshb/Semantic-UI-React
import React from 'react' import Types from './Types' import Variations from './Variations' const SearchExamples = () => ( <div> <Types /> <Variations /> </div> ) export default SearchExamples
app/components/Link/index.js
minhnhat09/scalable-react
/** * * Link * */ import React from 'react'; import styles from './styles.css'; function Link({link}) { return ( <div className={styles.link}> <div className={styles.votingContainer}> <div className={styles.votingCount}> {link.voteCount} </div> </div> <div className={styles.detailsContainer}> <div> <a href={link.url} className={styles.linkAnchor}>{link.url}</a> </div> <div className={styles.description}> {link.description} </div> </div> </div> ); } Link.propTypes = { link: React.PropTypes.shape({ description: React.PropTypes.string.isRequired, url: React.PropTypes.string.isRequired, id: React.PropTypes.string.isRequired, }), }; export default Link;
components/Input/stories.js
insane-ux/rebulma
// @flow import React from 'react' import { storiesOf } from '@kadira/storybook' import Label from 'components/Label' import Input from './' storiesOf('Input', module).add('all', () => ( <div className="box"> <Label>default</Label> <Input /> <Label>small</Label> <Input theme={{ input: 'is-small' }} /> <Label>loading</Label> <Input className="is-loading" /> <Label>read only</Label> <Input readOnly /> <Label>disabled</Label> <Input disabled /> <Label>with left icon</Label> <Input leftIcon="fa-pencil-square-o" theme={{ input: 'is-large' }} /> <Label>with right icon</Label> <Input rightIcon="fa-pencil-square-o" theme={{ input: 'is-small', leftIcon: 'is-small' }} /> <Label>with color</Label> <Input rightIcon="fa-pencil-square-o" theme={{ input: 'is-danger' }} /> <Label>with both icon</Label> <Input leftIcon="fa-pencil-square-o" rightIcon="fa-check" theme={{ leftIcon: 'is-small' }} /> </div> ))
tools/template/index/container/index.js
SteamerTeam/steamer-react
import React, { Component } from 'react'; import Connect from '../connect/connect'; import { } from 'page/common/constants/cgiPath'; import { } from '../constants/constants'; import './index.less'; class Wrapper extends Component { constructor(props, context) { super(props, context); this.state = {}; } componentDidMount() { } render() { return ( <div>hello world</div> ); } } export default Connect(Wrapper);
tp-react/src/App.js
detienne11/imie
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Test from './Test'; class App extends Component { constructor(props){ super(props); console.log("App : constructor"); console.log("App: props", props); } componentWillMount(){ console.log("App : componentWillMount"); } componentDidMount() { console.log("App : componentDidMount"); } render() { console.log("App : render"); return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2 style={{color: this.props.color}}>Salut to React</h2> </div> <p className="App-intro"> <Test /> </p> </div> ); } } export default App;
public/js/cat_source/es6/components/icons/Icon3Dots.js
matecat/MateCat
import React from 'react' const Icon3Dots = () => { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="5 5 32 32"> <g fill="#fff" fillRule="evenodd" transform="translate(9 9)"> <circle cx="12.5" cy="2.5" r="2.5" /> <circle cx="12.5" cy="21.5" r="2.5" /> <circle cx="12.5" cy="12.5" r="2.5" /> </g> </svg> ) } export default Icon3Dots
templates/rubix/rubix-bootstrap/src/Button.js
jeffthemaximum/Teachers-Dont-Pay-Jeff
import React from 'react'; import classNames from 'classnames'; import RButton from 'react-bootstrap/lib/Button'; var expectedTypes = ["success", "warning", "danger", "info", "default", "primary", "link"]; function isBtnOfType(type) { for (var i = 0; i < expectedTypes.length; i++) { if (expectedTypes[i] === type) { return true; } } return false; } export default class Button extends React.Component { static propTypes = { xs: React.PropTypes.bool, sm: React.PropTypes.bool, lg: React.PropTypes.bool, rounded: React.PropTypes.bool, onlyOnHover: React.PropTypes.bool, retainBackground: React.PropTypes.bool, inverse: React.PropTypes.bool, outlined: React.PropTypes.bool, }; render() { let props = {...this.props}; if (props.close) { console.error('Button "close" prop has been deprecated in Rubix v4.0.0'); } if (props.xs) { props.bsSize = 'xsmall'; delete props.xs; } if (props.sm) { props.bsSize = 'small'; delete props.sm; } if (props.lg) { props.bsSize = 'large'; delete props.lg; } if (props.hasOwnProperty('bsStyle') && typeof props.bsStyle === 'string') { var styles = props.bsStyle.split(/\s|\,/mgi).filter((a) => a); for (var i = 0; i < styles.length; i++) { if (isBtnOfType(styles[i])) { props.bsStyle = styles[i]; } else { props.className = classNames(props.className, 'btn-' + styles[i]); props.bsStyle = 'default'; } } } if (props.retainBackground) { props.className = classNames(props.className, 'btn-retainBg'); } if (props.rounded) { props.className = classNames(props.className, 'btn-rounded'); } if (props.onlyOnHover) { props.className = classNames(props.className, 'btn-onlyOnHover'); } if (props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-inverse'); } if (props.outlined || props.onlyOnHover || props.inverse || props.retainBackground) { props.className = classNames(props.className, 'btn-outlined'); } delete props.retainBackground; delete props.rounded; delete props.onlyOnHover; delete props.inverse; delete props.outlined; return ( <RButton {...props} /> ); } }
src/routes/UIElement/search/index.js
cuijiaxu/react-front
import React from 'react' import { Search } from '../../../components' import { Table, Row, Col, Card } from 'antd' const SearchPage = () => <div className="content-inner"> <Row gutter={32}> <Col lg={8} md={12}> <Card title="默认"> <Search /> </Card> </Col> <Col lg={8} md={12}> <Card title="附带选择"> <Search {...{ select: true, selectOptions: [ { value: 'components', name: '组件' }, { value: 'page', name: '页面' }, ], selectProps: { defaultValue: 'components', }, }} /> </Card> </Col> <Col lg={8} md={12}> <Card title="大小"> <Search size="large" style={{ marginBottom: 16 }} /> <Search size="small" /> </Card> </Col> </Row> <h2 style={{ margin: '16px 0' }}>Props</h2> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: '参数', dataIndex: 'props', }, { title: '说明', dataIndex: 'desciption', }, { title: '类型', dataIndex: 'type', }, { title: '默认值', dataIndex: 'default', }, ]} dataSource={[ { props: 'size', desciption: '设置Search大小,可选值为 【small】 【large】 或者不设', type: 'String', default: '-', }, { props: 'select', desciption: '设置是否有选择器', type: 'Boolean', default: 'false', }, { props: 'selectOptions', desciption: '选择器的选项,格式为[{name:"",value:""}]或者[{value:""}]', type: 'Array', default: '-', }, { props: 'selectProps', desciption: '选择器的属性,可参考antd的【Select】组件', type: 'Object', default: '-', }, { props: 'onSearch', desciption: '点击搜索按钮, 按Enter键或者点击清除时的回调', type: 'Function({keyword:string,field:string})', default: '-', }, ]} /> </Col> </Row> </div> export default SearchPage
app/react-icons/fa/maxcdn.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaMaxcdn extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m39.5 17.3l-3.7 17h-7.5l4-18.6q0.3-1.2-0.3-1.9-0.6-0.8-1.9-0.8h-3.8l-4.5 21.3h-7.5l4.6-21.3h-6.4l-4.5 21.3h-7.5l4.6-21.3-3.5-7.3h28.5q2.3 0 4.2 0.9t3.3 2.6q1.4 1.6 1.9 3.7t0 4.4z"/></g> </IconBase> ); } }
app/javascript/mastodon/components/intersection_observer_article.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import scheduleIdleTask from '../features/ui/util/schedule_idle_task'; import getRectFromEntry from '../features/ui/util/get_rect_from_entry'; // Diff these props in the "unrendered" state const updateOnPropsForUnrendered = ['id', 'index', 'listLength', 'cachedHeight']; export default class IntersectionObserverArticle extends React.Component { static propTypes = { intersectionObserverWrapper: PropTypes.object.isRequired, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), saveHeightKey: PropTypes.string, cachedHeight: PropTypes.number, onHeightChange: PropTypes.func, children: PropTypes.node, }; state = { isHidden: false, // set to true in requestIdleCallback to trigger un-render } shouldComponentUpdate (nextProps, nextState) { const isUnrendered = !this.state.isIntersecting && (this.state.isHidden || this.props.cachedHeight); const willBeUnrendered = !nextState.isIntersecting && (nextState.isHidden || nextProps.cachedHeight); if (!!isUnrendered !== !!willBeUnrendered) { // If we're going from rendered to unrendered (or vice versa) then update return true; } // If we are and remain hidden, diff based on props if (isUnrendered) { return !updateOnPropsForUnrendered.every(prop => nextProps[prop] === this.props[prop]); } // Else, assume the children have changed return true; } componentDidMount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.observe( id, this.node, this.handleIntersection, ); this.componentMounted = true; } componentWillUnmount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.unobserve(id, this.node); this.componentMounted = false; } handleIntersection = (entry) => { this.entry = entry; scheduleIdleTask(this.calculateHeight); this.setState(this.updateStateAfterIntersection); } updateStateAfterIntersection = (prevState) => { if (prevState.isIntersecting !== false && !this.entry.isIntersecting) { scheduleIdleTask(this.hideIfNotIntersecting); } return { isIntersecting: this.entry.isIntersecting, isHidden: false, }; } calculateHeight = () => { const { onHeightChange, saveHeightKey, id } = this.props; // save the height of the fully-rendered element (this is expensive // on Chrome, where we need to fall back to getBoundingClientRect) this.height = getRectFromEntry(this.entry).height; if (onHeightChange && saveHeightKey) { onHeightChange(saveHeightKey, id, this.height); } } hideIfNotIntersecting = () => { if (!this.componentMounted) { return; } // When the browser gets a chance, test if we're still not intersecting, // and if so, set our isHidden to true to trigger an unrender. The point of // this is to save DOM nodes and avoid using up too much memory. // See: https://github.com/mastodon/mastodon/issues/2900 this.setState((prevState) => ({ isHidden: !prevState.isIntersecting })); } handleRef = (node) => { this.node = node; } render () { const { children, id, index, listLength, cachedHeight } = this.props; const { isIntersecting, isHidden } = this.state; if (!isIntersecting && (isHidden || cachedHeight)) { return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} style={{ height: `${this.height || cachedHeight}px`, opacity: 0, overflow: 'hidden' }} data-id={id} tabIndex='0' > {children && React.cloneElement(children, { hidden: true })} </article> ); } return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} data-id={id} tabIndex='0'> {children && React.cloneElement(children, { hidden: false })} </article> ); } }
src/layouts/index.js
matchilling/com-matchilling
import React from 'react' import { Container } from 'react-responsive-grid' import Fullscreen from './../components/fullscreen/' import { rhythm, scale } from './../utils/typography' // Import typefaces import 'typeface-montserrat' import 'typeface-merriweather' import './prism.css' import './util.css' export default class Template extends React.Component { render() { const { location, children } = this.props, rootPath = typeof __PREFIX_PATHS__ !== `undefined` && __PREFIX_PATHS__ ? __PATH_PREFIX__ + `/` : `/` return ( <div> {location.pathname === rootPath && ( <div> <Fullscreen /> {children()} </div> )} {location.pathname !== rootPath && ( <div> <div style={{ borderWidth: `${rhythm(0.3)}`, borderTopStyle: `solid`, }} /> <Container style={{ maxWidth: rhythm(22), padding: `${rhythm(1.5)} ${rhythm(3 / 4)}`, }} > <h3 style={{ fontFamily: 'Montserrat, sans-serif', marginTop: 0, marginBottom: rhythm(-1), }} > <a style={{ boxShadow: 'none', color: 'inherit', marginRight: rhythm(0.2), textDecoration: 'none', }} href={'/'} > Home </a> {'/contact/' === location.pathname && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> Contact </span> )} {'/project/' === location.pathname && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> Project </span> )} {-1 === ['/contact/', '/project/', rootPath].indexOf( location.pathname, ) && ( <span> <span style={{ boxShadow: 'none', color: 'hsla(0,0%,0%,0.5)', marginRight: rhythm(0.2), textDecoration: 'none', }} > / </span> <a style={{ boxShadow: 'none', color: 'inherit', textDecoration: 'none', }} href={'/blog/'} > Blog </a> </span> )} </h3> {children()} </Container> </div> )} </div> ) } }
src/components/SideBarNavigation.js
tofuness/Toshocat
import React from 'react'; import { Link } from 'react-router'; const SideBarNavigation = () => { return ( <div className="sidebar-navigation"> <div className="sidebar-navigation-label"> Main </div> <div className="sidebar-navigation-link"> <Link to="/animelist" activeClassName="active"> <span className="icon-three-bars"></span>Anime list </Link> </div> <div className="sidebar-navigation-link"> <Link to="/mangalist" activeClassName="active"> <span className="icon-three-bars"></span>Manga list </Link> </div> <div className="sidebar-navigation-spacer"></div> <div className="sidebar-navigation-label"> Browse </div> <div className="sidebar-navigation-link"> <Link to="/calendar" activeClassName="active"> <span className="icon-calendar"></span>Calendar </Link> </div> <div className="sidebar-navigation-link hide"> <Link to="/chart" activeClassName="active"> <span className="icon-map"></span>Season Charts </Link> </div> <div className="sidebar-navigation-link"> <Link to="/search" activeClassName="active"> <span className="icon-search"></span>Search </Link> </div> <div className="sidebar-navigation-spacer"></div> <div className="sidebar-navigation-label"> System </div> <div className="sidebar-navigation-link"> <Link to="/settings" activeClassName="active"> <span className="icon-gear"></span>Settings </Link> </div> </div> ); }; export default SideBarNavigation;
src/js/components/plan/PlanFilesTab.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import ClassNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import React from 'react'; import { Set } from 'immutable'; import FileList from './FileList'; const PlanFilesTab = ({ active, ...rest }) => ( <div className={ClassNames({ 'tab-pane': true, active: active })}> <FileList {...rest} /> </div> ); PlanFilesTab.propTypes = { active: PropTypes.bool.isRequired, planFiles: ImmutablePropTypes.set.isRequired, selectedFiles: PropTypes.array.isRequired }; PlanFilesTab.defaultProps = { active: false, planFiles: Set() }; export default PlanFilesTab;
src/components/FAQ/List/List-story.js
Tarabyte/foodlr-web
import React from 'react' import { storiesOf } from '@kadira/storybook' import List from './List' const questions = [ { question: 'sdfsdf', answer: '<p>sdfsddsffd</p>', id: '54dbb245f08e85d01b3ef0ec' }, { question: 'fds', answer: '<p>sdfsdfsdffsfdsd</p>', id: '54dbaf16f08e85d01b3ef0eb' }, { question: 'sdfsd', answer: '<p>sdfsdfsd</p>', id: '54dbb45715240be82738d98e' }, { question: 'sdfsdf', answer: '<p>sdfsdfsdf</p>', id: '54dbb2f6f08e85d01b3ef0ed' } ] storiesOf('FAQ-List', module) .add('Empty', () => <List questions={[]} />) .add('With questions', () => <List questions={questions} />)
src/js/components/Dashboard.js
varmais/spteefu
import React from 'react'; import Header from './Header'; import Sidebar from './Sidebar'; import AlbumList from './AlbumList'; import ArtistStore from '../stores/ArtistStore'; import ArtistService from '../services/ArtistService'; import AlbumStore from '../stores/AlbumStore'; import AlbumService from '../services/AlbumService'; class Dashboard extends React.Component { constructor() { super(); this.state = { artists: this._getArtists(), albums: this._getAlbums() }; } componentDidMount() { if (!this.state.artists.length) { this._requestArtists(); } ArtistStore.addChangeListener(this._onChange.bind(this)); AlbumStore.addChangeListener(this._onChange.bind(this)); } componentWillUnmount() { ArtistStore.removeChangeListener(this._onChange.bind(this)); AlbumStore.removeChangeListener(this._onChange.bind(this)); } _onChange() { var artists = this._getArtists(); var albums = this._getAlbums(); this.setState({artists, albums}); } _requestArtists() { ArtistService.getArtists(); } _getArtists() { return ArtistStore.artists; } _getAlbums() { return AlbumStore.albums; } render() { return ( <div className="dashboard-container"> <Header /> <Sidebar artists={this.state.artists} /> <AlbumList albums={this.state.albums} /> </div> ); } } export default Dashboard;
app/containers/HomePage/index.js
rhenderson07/react-lightning-talk
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/index.js
azimitina/post-list-redux
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom' import promise from 'redux-promise' import reducers from './reducers' import PostsIndex from './components/posts_index' import PostsNew from './components/posts_new' import PostsShow from './components/posts_show' const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew} /> <Route path="/posts/:id" component={PostsShow} /> <Route path="/" component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
src/components/base/NotFoundPage.js
GHImplementationTeam/FrontEnd
import React from 'react'; const NotFoundPage = () => ( <div> <div> 404 Page Not Found </div> </div> ); export default NotFoundPage;
docs/app/Examples/elements/Label/Types/LabelExampleImageColored.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Label } from 'semantic-ui-react' const LabelExampleImage = () => ( <div> <Label as='a' color='blue' image> <img src='http://semantic-ui.com/images/avatar/small/veronika.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='teal' image> <img src='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> Veronika <Label.Detail>Friend</Label.Detail> </Label> <Label as='a' color='yellow' image> <img src='http://semantic-ui.com/images/avatar/small/christian.jpg' /> Helen <Label.Detail>Co-worker</Label.Detail> </Label> </div> ) export default LabelExampleImage
blueocean-material-icons/src/js/components/svg-icons/image/rotate-right.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageRotateRight = (props) => ( <SvgIcon {...props}> <path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"/> </SvgIcon> ); ImageRotateRight.displayName = 'ImageRotateRight'; ImageRotateRight.muiName = 'SvgIcon'; export default ImageRotateRight;
app/components/FacetList/index.js
interra/data-generate
import React from 'react'; import PropTypes from 'prop-types'; import List from 'components/List'; import ListItem from 'components/ListItem'; import LoadingIndicator from 'components/LoadingIndicator'; import SearchListItem from 'containers/SearchListItem'; import H3 from './H3'; import LI from './LI'; import StyledA from './StyledA'; import FacetBlockDiv from './FacetBlockDiv'; function FacetBlocks({ title, items, facetKey, loading, click, selectedFacets }) { if (loading) { return <FacetBlockDiv><h4>{title}</h4><List component={LoadingIndicator} /></FacetBlockDiv>; } let content = (<ul></ul>); content = items[facetKey].map(function callback(facet, i) { const name = facet[0]; var value = "(" + facet[1] + ")"; let active = false; if (selectedFacets) { selectedFacets.forEach(function(facet) { if (facetKey == facet[0] && name == facet[1]) { active = 'active'; value = "" } }); } return <LI key={`facet-${i}`}><StyledA data-facet-type={facetKey} className={active} onClick={click} href={`#facet-${title}-${name}`}>{name} {value}</StyledA></LI> }); return <FacetBlockDiv><h4>{title}</h4><ul className="list-group" key="items">{content}</ul></FacetBlockDiv>; } function FacetList({ facets, loadingFacets, loadingFacetsResults, selectedFacets, facetsResults, facetClick }) { let content = (<div></div>); if (loadingFacets) { return <List component={LoadingIndicator} />; } if (facets !== false) { let items = []; for (var facet in facets) { items.push(facet); } content = items.map((item) => ( <FacetBlocks title={facets[item].label} key={item} facetKey={item} selectedFacets={selectedFacets} items={facetsResults} click={facetClick} loading={loadingFacetsResults} /> )); return <div key="facets">{content}</div>; } return null; } FacetList.propTypes = { facets: PropTypes.any, facetsLoading: PropTypes.any, }; export default FacetList;
src/client/spinner.js
alihalabyah/hacker-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Loading... </div> ) } }
src/BootstrapMixin.js
tannewt/react-bootstrap
import React from 'react'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const BootstrapMixin = { propTypes: { /** * bootstrap className * @private */ bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES), /** * Style variants * @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")} */ bsStyle: React.PropTypes.oneOf(styleMaps.STYLES), /** * Size variants * @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")} */ bsSize: CustomPropTypes.keyOf(styleMaps.SIZES) }, getBsClassSet() { let classes = {}; let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; let prefix = bsClass + '-'; let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } if (this.props.bsStyle) { if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) { classes[prefix + this.props.bsStyle] = true; } else { classes[this.props.bsStyle] = true; } } } return classes; }, prefixClass(subClass) { return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass; } }; export default BootstrapMixin;
src/svg-icons/editor/border-style.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderStyle = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4 0h2v-2h-2v2zM7 21h2v-2H7v2zm4 0h2v-2h-2v2zm8-4h2v-2h-2v2zm0-4h2v-2h-2v2zM3 3v18h2V5h16V3H3zm16 6h2V7h-2v2z"/> </SvgIcon> ); EditorBorderStyle = pure(EditorBorderStyle); EditorBorderStyle.displayName = 'EditorBorderStyle'; EditorBorderStyle.muiName = 'SvgIcon'; export default EditorBorderStyle;
src/Pages/LandingPage.js
ashwinath/personal-website-2.0
import React from 'react'; const LandingPage = () => ( <div id="landing" className="col-md-9 main-section center-vertical-parent"> <div id="landing-content" className="center-vertical"> <h1>I bring ideas to life with code.</h1> </div> </div> ); export default LandingPage;
frontend/blueprints/dumb/files/__root__/components/__name__/__name__.js
qurben/mopidy-jukebox
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/index.js
lucaslago/baratinho-frontend
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import createLogger from 'redux-logger' import thunkMiddleware from 'redux-thunk' import App from './components/App' import Home from './scenes/Home' import rootReducer from './reducers' import { fetchPromotions } from './actions' const loggerMiddleware = createLogger() const store = createStore(rootReducer, applyMiddleware(thunkMiddleware, loggerMiddleware)) store.dispatch(fetchPromotions()) .then(() => console.log(store.getState())) render( <Provider store={store}> <App> <Home /> </App> </Provider> , document.getElementById('root') )
consoles/my-joy-instances/src/containers/navigation/breadcrumb.js
yldio/joyent-portal
import React from 'react'; import paramCase from 'param-case'; import get from 'lodash.get'; import { Link } from 'react-router-dom'; import { Margin } from 'styled-components-spacing'; import { Breadcrumb, BreadcrumbItem } from 'joyent-ui-toolkit'; export default ({ match }) => { const instance = get(match, 'params.instance'); const links = [ { name: 'Compute', pathname: '/' }, { name: 'Instances', pathname: '/instances' } ] .concat( instance && [ { name: paramCase(instance), pathname: `/instances/${instance}` } ] ) .filter(Boolean) .map(({ name, pathname }) => ( <BreadcrumbItem key={name} to={pathname} component={Link}> <Margin horizontal="1" vertical="3"> {name} </Margin> </BreadcrumbItem> )); return <Breadcrumb>{links}</Breadcrumb>; };
node_modules/react-router/es6/Link.js
rekyyang/ArtificalLiverCloud
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { var allowTransition = true; if (this.props.onClick) this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (event.defaultPrevented === true) allowTransition = false; // If target prop is set (e.g. to "_blank") let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) { if (!allowTransition) event.preventDefault(); return; } event.preventDefault(); if (allowTransition) { var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(_location); } }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(_location2); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(_location2, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
yycomponent/locale-provider/LocaleProvider.js
77ircloud/yycomponent
import React from 'react'; import { LocaleProvider as _LocaleProvider } from 'antd'; class LocaleProvider extends React.Component{ constructor(props){ super(props); } render(){ return (<_LocaleProvider {...this.props}/>); } } export default LocaleProvider
src/routes/Login.js
Anteoy/lionreact
import React from 'react'; import { connect } from 'dva'; import styles from './Login.css'; // import PnoteIndex from '../components/login/Login'; function Login() { return ( <div className={styles.normal}> {/* extra={<PnoteIndex />}*/} test </div> ); } function mapStateToProps() { return {}; } export default connect(mapStateToProps)(Login);
src/svg-icons/communication/screen-share.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationScreenShare = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/> </SvgIcon> ); CommunicationScreenShare = pure(CommunicationScreenShare); CommunicationScreenShare.displayName = 'CommunicationScreenShare'; CommunicationScreenShare.muiName = 'SvgIcon'; export default CommunicationScreenShare;
src/components/NotFoundPage.js
Dynatos/personal-website
import React from 'react'; //import { Link } from 'react-router'; import { Link } from "react-router-dom"; import NavBar from './NavBar/NavBar'; const NotFoundPage = () => { return ( <div> <NavBar/> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
app/javascript/mastodon/components/loading_indicator.js
salvadorpla/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const LoadingIndicator = () => ( <div className='loading-indicator'> <div className='loading-indicator__figure' /> <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' /> </div> ); export default LoadingIndicator;
src/components/views/delegateProfile/components/Sidebar.js
LiskHunt/LiskHunt
import React from 'react'; import Description from './Description'; import BannerWrap from './BannerWrap'; import HeaderCard from './HeaderCard'; const Sidebar = () => { return ( <div id="sidebar" className="column is-one-quarter"> <BannerWrap /> <HeaderCard /> <Description /> </div> ); }; export default Sidebar;
modules/client.js
Scarysize/browserify-code-split
import React from 'react'; import { match, Router } from 'react-router'; import { render } from 'react-dom'; import { createHistory } from 'history'; import routes from './routes/RootRoute'; const { pathname, search, hash } = window.location; const location = `${pathname}${search}${hash}`; // calling `match` is simply for side effects of // loading route/component code for the initial location match({ routes, location }, () => { render( <Router routes={routes} history={createHistory()} />, document.getElementById('app') ); });
src/utils/CustomPropTypes.js
IveWong/react-bootstrap
import React from 'react'; const ANONYMOUS = '<<anonymous>>'; const CustomPropTypes = { isRequiredForA11y(propType){ return function(props, propName, componentName){ if (props[propName] === null) { return new Error( 'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `' ); } return propType(props, propName, componentName); }; }, /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ elementType: createElementTypeChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker, all }; function errMsg(props, propName, componentName, msgContinuation) { return `Invalid prop '${propName}' of value '${props[propName]}'` + ` supplied to '${componentName}'${msgContinuation}`; } /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error( `Required prop '${propName}' was not specified in '${componentName}'.` ); } } else { return validate(props, propName, componentName); } } let chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error( errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method') ); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { let propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { let valuesString = JSON.stringify(Object.keys(obj)); return new Error( errMsg(props, propName, componentName, `, expected one of ${valuesString}.`) ); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName, componentName) { const usedPropCount = arrOfProps .map(listedProp => props[listedProp]) .reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0); if (usedPropCount > 1) { const [first, ...others] = arrOfProps; const message = `${others.join(', ')} and ${first}`; return new Error( `Invalid prop '${propName}', only one of the following ` + `may be provided: ${message}` ); } } return validate; } function all(propTypes) { if (propTypes === undefined) { throw new Error('No validations provided'); } if (!(propTypes instanceof Array)) { throw new Error('Invalid argument must be an array'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } return function(props, propName, componentName) { for(let i = 0; i < propTypes.length; i++) { let result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } }; } function createElementTypeChecker() { function validate(props, propName, componentName) { let errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (React.isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } return createChainableTypeChecker(validate); } export default CustomPropTypes;
blueocean-material-icons/src/js/components/svg-icons/av/games.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvGames = (props) => ( <SvgIcon {...props}> <path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/> </SvgIcon> ); AvGames.displayName = 'AvGames'; AvGames.muiName = 'SvgIcon'; export default AvGames;
plugins/Files/js/components/downloadlist.js
NebulousLabs/Sia-UI
import PropTypes from 'prop-types' import React from 'react' import TransferList from './transferlist.js' import { List } from 'immutable' const DownloadList = ({ downloads, onDownloadClick, onClearClick }) => ( <div className='downloads'> <h3> Downloads </h3> <TransferList transfers={downloads} onTransferClick={onDownloadClick} /> <button onClick={onClearClick} className='clear-downloads'> Clear Downloads </button> </div> ) DownloadList.propTypes = { downloads: PropTypes.instanceOf(List).isRequired, onDownloadClick: PropTypes.func, onClearClick: PropTypes.func } export default DownloadList
src/svg-icons/av/snooze.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSnooze = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/> </SvgIcon> ); AvSnooze = pure(AvSnooze); AvSnooze.displayName = 'AvSnooze'; AvSnooze.muiName = 'SvgIcon'; export default AvSnooze;
examples/real-world/containers/DevTools.js
tappleby/redux
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> )
src/lib/components/D3/ScatterPlotUI.js
as-me/Adapter
import "d3chart"; import React from 'react'; class D3ScatterPlot extends React.Component { constructor(props) { super(props); this.sessionData = props.sessionData; this.hook = props.hook; this.state = this.sessionData.getSessionStateValue(); this.initialize = this.initialize.bind(this); this._setReactState = this._setReactState.bind(this); } initialize() { var _dataSourcePath = this.state.dataSourcePath; //since key wasnt mentioned here it creates index column and name index as key column name if (_dataSourcePath && _dataSourcePath.length > 0) { var config = { container: React.findDOMNode(this), margin: this.props.padding ? this.props.padding : {}, size: this.props.size ? this.props.size : {}, interactions: { onProbe: this.props.onProbe, onSelect: this.props.onSelect } } this.hook.chart = new d3Chart.Scatterplot(); this.hook.chart.create(config); var path = this.state.dataSourcePath; var rows = WeaveAPI.SessionManager.getObject(WeaveAPI.globalHashMap, path).data.getSessionState(); var data = { columns: { x: this.state.xAxis, y: this.state.yAxis }, records: rows }; console.log('d3', rows); this.hook.chart.renderChart(data); } else { console.warn("No data"); } } //tied with d3 creation componentDidMount() { this.initialize(); // make sure data update is called last , so that x and y axis property will be ready by then. WeaveAPI.SessionManager.getCallbackCollection(this.sessionData).addGroupedCallback(this, this._setReactState, true); } _setReactState() { if (!this.hook.chart) { this.initialize(); } this.setState(this.sessionData.getSessionStateValue()); } //tied with d3 update componentDidUpdate(prevProps, prevState) { if (this.hook.chart) { var path = this.state.dataSourcePath; var rows = WeaveAPI.SessionManager.getObject(WeaveAPI.globalHashMap, path).data.getSessionState(); var data = { columns: { x: this.state.xAxis, y: this.state.yAxis }, records: rows }; this.hook.chart.renderChart(data); } } //tied with d3 destruction componentWillUnmount() { WeaveAPI.SessionManager.getCallbackCollection(this.sessionData).removeCallback(this._setReactState); } render() { var _dataSourcePath = this.state.dataSourcePath; if (_dataSourcePath && _dataSourcePath.length > 0) { return <div className = 'Chart' > < /div>; } else { return <div className = 'Chart' > < h2 > { this.sessionData.dataSourceName } dont have data < /h2> < /div > ; } } } module.exports = D3ScatterPlot;
client/components/CodeEditor/index.js
Elektro1776/Project_3
import React, { Component } from 'react'; import LanguageDropdown from './Language_Dropdown'; import EditorField from './Code_Editor'; class CodeEditorParent extends Component { state = { currentLanguage: 'javascript' }; whatIsOurState(propVal) { this.setState({ currentLanguage: propVal }); } render() { return ( <div> <LanguageDropdown handleParentStateChange={this.whatIsOurState.bind(this)} /> <EditorField currentLanguageState={this.state.currentLanguage} /> </div> ); } } export default CodeEditorParent;
app/routes/notFound/index.js
wojciech-panek/study-group-6-redux
import React from 'react'; import { IndexRoute } from 'react-router'; import { NotFound } from './notFound.component'; export default ( <IndexRoute component={NotFound} /> );
src/components/examples/constructorFunc.js
Jguardado/ComponentBase
import React, { Component } from 'react'; /** * Class respresenting a Constructor Function * @constructor */ export default class Contructor extends Component { constructor(props) { super(props); /** intializing the state of the component */ this.state = { /** Anything assigned in the state object will be the intial values */ test: 'Created on initializaton', }; } render() { /** * @return The JSX represenation of a constructor functiom */ return ( <div className='center'> <legend className='headingtext'>Example Constructor</legend> {this.state.test} </div> ); } }
app/assets/javascripts/NewNodeWidget/Section/NodeTypeSelect.js
sozialhelden/wheelmap
import React from 'react'; import sortBy from 'lodash.sortby'; import Form from '../../common/Form'; import I18n from '../../common/I18n'; import { Category, NodeType } from '../../common/models'; import { immutableMapOf } from '../../common/propTypes'; const { func, instanceOf, string } = React.PropTypes; class NodeTypeSelect extends React.Component { static propTypes = { onChange: func, categories: immutableMapOf(instanceOf(Category)), nodeTypes: immutableMapOf(instanceOf(NodeType)), value: string }; onChange = event => { this.props.onChange(event.target.value); }; getOptions() { const { categories, nodeTypes } = this.props; const optGroups = categories.toArray().map(category => { const options = nodeTypes .filter(nodeType => nodeType.category === category.id) .toArray() .map(nodeType => ({ label: I18n.t(`poi.name.${category.identifier}.${nodeType.identifier}`), value: nodeType.identifier })); return { label: I18n.t(`poi.category.${category.identifier}`), options: sortBy(options, 'label') }; }); return sortBy(optGroups, 'label'); } render() { return ( <Form.Select options={this.getOptions()} onChange={this.onChange} value={this.props.value} /> ); } } export default NodeTypeSelect;
tp-3/sebareverso/src/components/pages/about/AboutPage.js
jpgonzalezquinteros/sovos-reactivo-2017
import React from 'react'; import Paper from 'material-ui/Paper'; import '../../app.scss'; import {Card, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; class AboutPage extends React.Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpandChange = (expanded) => { this.setState({expanded: expanded}); }; render() { return ( <div> <Paper zDepth={2} className='paperStyle' > <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}> <CardHeader title="Sebasti&aacute;n Reverso" subtitle="Sovos Reactivo" avatar="./profile.jpg" actAsExpander={true} showExpandableButton={true} /> <CardMedia expandable={true} overlay={<CardTitle title="Sebasti&aacute;n Reverso" subtitle="Sovos Reactivo" />} > <img src="./profile.jpg" alt="" /> </CardMedia> <CardTitle title="Tuculegio" subtitle="Proyecto Reactivo" expandable={true} /> <CardText expandable={true}> Este es el proyecto Tuculegio desarrollado por los Reactivos 2017 de Sovos! </CardText> </Card> </Paper> </div> ); } } export default AboutPage;
src/containers/skill-tree/SkillTree.js
phodal/growth-ng
/* eslint-disable global-require */ /* global __DEV__, require */ import React, { Component } from 'react'; import { WebView, StyleSheet, Platform } from 'react-native'; import { Actions } from 'react-native-router-flux'; import AppSizes from '../../theme/sizes'; import AppStyles from '../../theme/styles'; import SKILL_TREE_DATA from './SKILL_TREE_DATA'; const filter = require('lodash.filter'); const styles = StyleSheet.create({ container: { height: AppSizes.screen.height, width: AppSizes.screen.width, }, }); class SkillTree extends Component { static componentName = 'SkillTree'; constructor() { super(); this.webview = null; } handleMessage = (event: Object) => { const message = event.nativeEvent.data; const skillId = parseInt(JSON.parse(message).id, 10); const title = filter(SKILL_TREE_DATA, { id: skillId })[0].title; Actions.skillDetail({ skillId, title }); }; render = () => { let source; if (__DEV__) { source = require('./www/index.html'); } else { source = Platform.OS === 'ios' ? require('./www/index.html') : { uri: 'file:///android_asset/skilltree/index.html' }; } return ( <WebView ref={(webview) => { this.webview = webview; }} scalesPageToFit startInLoadingState onMessage={this.handleMessage} source={source} automaticallyAdjustContentInsets={false} style={[AppStyles.container, styles.container]} injectedJavaScript="" onNavigationStateChange={this.onNavigationStateChange} /> ); } } export default SkillTree;
src/index.js
kgosse/productapp
require('./styles/main.scss'); import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render(<App />, document.getElementById('root'));
src/svg-icons/action/assignment-return.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentReturn = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm4 12h-4v3l-5-5 5-5v3h4v4z"/> </SvgIcon> ); ActionAssignmentReturn = pure(ActionAssignmentReturn); ActionAssignmentReturn.displayName = 'ActionAssignmentReturn'; ActionAssignmentReturn.muiName = 'SvgIcon'; export default ActionAssignmentReturn;
src/components/Match/Scoreboards/index.js
fooey/gw2w2w-cra
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import classnames from 'classnames'; import numeral from 'numeral'; // import Card from 'src/components/Layout/Card'; import { getWorldBySlug, getWorld, getWorldLink } from 'src/lib/world'; // import { getTeamColor } from 'src/lib/match'; class Scoreboards extends Component { render() { const { match, langSlug, worldSlug } = this.props; const matchWorld = getWorldBySlug(worldSlug); // const teamColor = getTeamColor(match.all_worlds, world.id); return ( <div className="match-scoreboards level-1"> {_.map(['red', 'blue', 'green'], color => ( <Scoreboard key={color} color={color} langSlug={langSlug} match={match} matchWorld={matchWorld} worldSlug={langSlug} /> ))} </div> ); } } class Scoreboard extends Component { render() { const { color, langSlug, match, matchWorld, // worldSlug, } = this.props; const worldId = _.get(match.worlds, `${color}_id`); const world = getWorld(worldId); const allWorldIds = _.without(_.get(match.all_worlds, `${color}_ids`), worldId); const score = _.get(match, ['scores', color]); const classes = classnames({ "match-scoreboard": true, active: world.id === matchWorld.id, [`team-${color}`]: true, // [`team-${color}-bg`]: true, }); return ( <div className={classes}> <h2 className={``}> <Link to={getWorldLink(world, langSlug)} className={`team-${color}`}> {_.get(world, [langSlug, 'name'])} </Link> </h2> <h3 key={worldId} className={``}> {_.map(allWorldIds, worldId => { const world = getWorld(worldId); return ( <Link key={worldId} to={getWorldLink(world, langSlug)} className={`team-${color}`}> {_.get(world, [langSlug, 'name'])} </Link> ); })} </h3> <div className='team-score'> {numeral(score).format('0,0')} </div> </div> ); } } export default Scoreboards;
client/views/admin/apps/CloudLoginModal.js
VoiSmart/Rocket.Chat
import { Button, ButtonGroup, Icon, Modal } from '@rocket.chat/fuselage'; import React from 'react'; import { useSetModal } from '../../../contexts/ModalContext'; import { useRoute } from '../../../contexts/RouterContext'; import { useTranslation } from '../../../contexts/TranslationContext'; const CloudLoginModal = (props) => { const t = useTranslation(); const setModal = useSetModal(); const cloudRoute = useRoute('cloud'); const handleCloseButtonClick = () => { setModal(null); }; const handleCancelButtonClick = () => { setModal(null); }; const handleLoginButtonClick = () => { cloudRoute.push(); setModal(null); }; return ( <Modal {...props}> <Modal.Header> <Icon color='danger' name='info-circled' size={20} /> <Modal.Title>{t('Apps_Marketplace_Login_Required_Title')}</Modal.Title> <Modal.Close onClick={handleCloseButtonClick} /> </Modal.Header> <Modal.Content fontScale='p1'> {t('Apps_Marketplace_Login_Required_Description')} </Modal.Content> <Modal.Footer> <ButtonGroup align='end'> <Button ghost onClick={handleCancelButtonClick}> {t('Cancel')} </Button> <Button primary danger onClick={handleLoginButtonClick}> {t('Login')} </Button> </ButtonGroup> </Modal.Footer> </Modal> ); }; export default CloudLoginModal;
examples/todomvc/containers/Root.js
jlongster/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
src/components/bet/BetFormModal.js
itjope/tipskampen
import React from 'react' import Dialog from 'material-ui/Dialog' import FlatButton from 'material-ui/FlatButton' const BetFormModal = (props) => { const actions = [ <FlatButton label='Cancel' secondary={true} onTouchTap={props.onCancel} />, <FlatButton label='Save' primary={true} onTouchTap={props.onSave} /> ] return <Dialog actions={actions} modal={true} contentStyle={{width: 330, minHeight: 700}} autoScrollBodyContent={true} // autoDetectWindowHeight={false} open={props.open} > {props.children} </Dialog> } BetFormModal.propTypes = { open: React.PropTypes.bool.isRequired, onCancel: React.PropTypes.func.isRequired, onSave: React.PropTypes.func.isRequired, children: React.PropTypes.element.isRequired } export default BetFormModal
src/components/Signin.js
ihenvyr/react-parse
import React from 'react'; import Form from './Form'; import Input from './Input'; import Button from './Button'; import Parse from 'parse'; import { withRouter } from 'react-router'; const Signin = ({ router }) => { const handleSubmit = (event) => { event.preventDefault(); const { username, password } = event.target; Parse.User.logIn(username.value, password.value, { success: (user) => router.push('/'), error: (user, error) => console.log(`Error: ${error.code} ${error.message}`), }); }; return ( <Form onSubmit={handleSubmit}> <h3>Sign In</h3> <p><Input name="username" type="text" placeholder="Username" required/></p> <p><Input name="password" type="password" placeholder="Password" required/></p> <Button type="submit" primary>Sign In</Button> </Form> ); }; Signin.propTypes = {}; Signin.defaultProps = {}; export default withRouter(Signin);
app/components/Navbar/NavDropdownDivider/index.js
josueorozco/parlay
import React from 'react'; import classNames from 'classnames'; /* |-------------------------------------------------------------------------- | NavDropdownDivider |-------------------------------------------------------------------------- | | Stateless component | */ const NavDropdownDivider = () => ( <div className={classNames( 'dropdown-divider', )} /> ); export default NavDropdownDivider;
client/app/containers/FeaturePage/index.js
jjt/ffsssshh
/* * FeaturePage * * List all the features */ import React from 'react'; import { connect } from 'react-redux'; import { routeActions } from 'react-router-redux'; import Button from 'Button'; import H1 from 'H1'; import A from 'A'; import styles from './styles.css'; class FeaturePage extends React.Component { constructor() { super(); this.onChangeRoute = this.onChangeRoute.bind(this); this.changeRouteToHome = this.changeRouteToHome.bind(this); } onChangeRoute(url) { this.props.changeRoute(url); } changeRouteToHome() { this.onChangeRoute('/'); } render() { return ( <div> <H1>Features</H1> <ul className={ styles.list }> <li className={ styles.listItem }> <p>Using <A href="https://github.com/gaearon/react-transform-hmr"><strong>react-transform-hmr</strong></A>, your changes in the CSS and JS get reflected in the app instantly without refreshing the page. That means that the <strong>current application state persists</strong> even when you change something in the underlying code! For a very good explanation and demo watch Dan Abramov himself <A href="https://www.youtube.com/watch?v=xsSnOQynTHs">talking about it at react-europe</A>.</p> </li> <li className={ styles.listItem }> <p><A href="https://github.com/gaearon/redux"><strong>Redux</strong></A> is a much better implementation of a flux–like, unidirectional data flow. Redux makes actions composable, reduces the boilerplate code and makes hot–reloading possible in the first place. For a good overview of redux check out the talk linked above or the <A href="https://gaearon.github.io/redux/">official documentation</A>!</p> </li> <li className={ styles.listItem }> <p><A href="https://github.com/postcss/postcss"><strong>PostCSS</strong></A> is like Sass, but modular and capable of much more. PostCSS is, in essence, just a wrapper for plugins which exposes an easy to use, but very powerful API. While it is possible to <A href="https://github.com/jonathantneal/precss">replicate Sass features</A> with PostCSS, PostCSS has an <A href="http://postcss.parts">ecosystem of amazing plugins</A> with functionalities Sass cannot even dream about having.</p> </li> <li className={ styles.listItem }> <p><strong>Unit tests</strong> should be an important part of every web application developers toolchain. <A href="https://github.com/mochajs/mocha">Mocha</A> checks your application is working exactly how it should without you lifting a single finger. Congratulations, you just won a First Class ticket to world domaination, fasten your seat belt please!</p> </li> <li className={ styles.listItem }> <p><A href="https://github.com/rackt/react-router"><strong>react-router</strong></A> is used for routing in this boilerplate. react-router makes routing really easy to do and takes care of a lot of the work.</p> </li> <li className={ styles.listItem }> <p><A href="http://www.html5rocks.com/en/tutorials/service-worker/introduction/"><strong>ServiceWorker</strong></A> and <A href="http://www.html5rocks.com/en/tutorials/appcache/beginner/"><strong>AppCache</strong></A> make it possible to use the application offline. As soon as the website has been opened once, it is cached and available without a network connection. <A href="https://developer.chrome.com/multidevice/android/installtohomescreen"><strong><code className={ styles.code }>manifest.json</code></strong></A> is specifically for Chrome on Android. Users can add the website to the homescreen and use it like a native app!</p> </li> </ul> <Button handleRoute= { this.changeRouteToHome } >Home</Button> </div> ); } } function mapStateToProps(state) { return { location: state.get('route').location }; } function mapDispatchToProps(dispatch) { return { changeRoute: (url) => dispatch(routeActions.push(url)) }; } export default connect(mapStateToProps, mapDispatchToProps)(FeaturePage);
src/svg-icons/notification/live-tv.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationLiveTv = (props) => ( <SvgIcon {...props}> <path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/> </SvgIcon> ); NotificationLiveTv = pure(NotificationLiveTv); NotificationLiveTv.displayName = 'NotificationLiveTv'; NotificationLiveTv.muiName = 'SvgIcon'; export default NotificationLiveTv;
components/Layout.js
Hardyng/weatherforecast-nextjs-redux-ssr
import React from 'react'; import cx from 'classnames'; import styled from 'styled-components'; // background-image: url('http://www.sciencemag.org/sites/default/files/styles/article_main_medium/public/images/ss-bird_honeycreeper.jpg?itok=eEm6TBrb'); import Header from './Header'; const Container = styled.div` background-size: cover; `; const Grid = styled.div` max-width: 1000px; ` class Layout extends React.Component { render() { return ( <Container className='mdl-layout__container'> <div className="mdl-layout mdl-js-layout mdl-layout--fixed-header"> <Header loading={this.props.loading}></Header> <main className="mdl-layout__content"> <Grid className="mdl-grid"> {this.props.children} </Grid> </main> </div> </Container> ) } } export default Layout
src/stretchView.js
guoyuan94/react-native-stretchview
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { StyleSheet, View, Animated, } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, }, }); export default class StretchView extends Component { constructor(props, context) { super(props, context); this.state = { animateHeight: new Animated.Value(0), }; } componentWillMount() { this.stretch = this.stretch.bind(this); } componentWillReceiveProps(nextProps) { const { expanded } = this.props; if (nextProps.expanded !== expanded) { this.stretch(nextProps.expanded); } } stretch(expanded) { const { stretchDuration, animateDistance, onAnimationStart, syncAnimations, onAnimationEnd, } = this.props; const { animateHeight } = this.state; const duration = stretchDuration; const toValue = expanded ? animateDistance : 0; if (onAnimationStart) { onAnimationStart(); } let animations = [ Animated.timing(animateHeight, { toValue, duration, }), ]; if (syncAnimations) { animations = animations.concat(syncAnimations()); } Animated.parallel(animations).start(); if (onAnimationEnd) { onAnimationEnd(duration, toValue); } } render() { const { expanded, renderTopFace, renderBottomFace, } = this.props; const { animateHeight } = this.state; const pointerEvents = expanded ? 'box-none' : 'auto'; return ( <View style={styles.container}> { renderTopFace() } <Animated.View style={{ height: animateHeight, overflow: 'hidden', }} pointerEvents={pointerEvents} > { renderBottomFace() } </Animated.View> </View> ); } } StretchView.propTypes = { stretchDuration: PropTypes.number, renderTopFace: PropTypes.func.isRequired, renderBottomFace: PropTypes.func.isRequired, animateDistance: PropTypes.number.isRequired, expanded: PropTypes.bool.isRequired, onAnimationEnd: PropTypes.func, onAnimationStart: PropTypes.func, syncAnimations: PropTypes.func, }; StretchView.defaultProps = { stretchDuration: 250, };
app/components/Main.js
luongthomas/React-Portfolio
import React from 'react'; import ReactCSSTtransitionGroup from 'react-addons-css-transition-group'; // we can do this syntax because of webpack loaders import '../main.css'; // Key from react router. CloneElement lets us attach a key to the "would-be component" // , aka new props // React keeps track of keys (order) or a list of items and their orders // ReactCSSTtransitionGroup needs its children to have keys const Main = React.createClass({ render() { return ( <div className='main-container'> <ReactCSSTtransitionGroup transitionName="appear" transitionEnterTimeout={500} transitionLeaveTimeout={500}> { React.cloneElement(this.props.children, { key: this.props.location.pathname })} </ReactCSSTtransitionGroup> </div> ); }, }); export default Main;
client/src/components/Task/TaskStepBaseClass.js
DemocracyGuardians/DGTeam
import React from 'react'; import PropTypes from 'prop-types' class TaskStepBaseClass extends React.Component { render() { return (<span></span>) } } TaskStepBaseClass.propTypes = { store: PropTypes.object.isRequired, content: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired, onStepComplete: PropTypes.func.isRequired, onRevertProgress: PropTypes.func.isRequired, hideShowWizardNavigation: PropTypes.func.isRequired } export default TaskStepBaseClass;
powerpiapp/elements/common/Header.js
Knapsacks/power-pi-v2
// import library import React from 'react'; import { Text, View } from 'react-native'; // create a component const Header = (props) => { const { textStyle, viewStyle } = styles; return ( <View style={viewStyle}> <Text style={textStyle}>{props.headerText}</Text> </View> ); }; const styles = { viewStyle: { backgroundColor: '#FDFFFC', alignItems: 'center', padding: 15, marginTop: 25, elevation: 10, position: 'relative', }, textStyle: { fontSize: 20, color: '#011627', fontWeight: 'bold' } }; // make component available to other part of apps export { Header };
src/components/Datepicker/Date.js
wiki1024/sam-bs
import React from 'react' import classnames from 'classnames' const Date = (props) => { let {id, date, month, selectDate, selected} = props let classes = classnames('date', { 'current': date.month() === month, 'future': date.month() > month, 'past': date.month() < month, 'selected': (date.date() === selected.date() && date.month() === selected.month() && date.year() === selected.year()), }) return ( <div className={classes} onClick={ (e)=> { selectDate({id:id,val:date});e.stopPropagation() } }> {date.date()} </div> ) } export default Date
src/List/List.js
abouthiroppy/scuba
// @flow import type { CommonProps } from '../CommonTypes'; import React from 'react'; import classnames from 'classnames'; import excludeProps from '../utils/excludeProps'; import styles from './style'; type Props= { type: 'none' | 'circle' | 'square' | 'decimal'; }; const List = (props: CommonProps & Props) => ( <ul {...excludeProps(props, ['type'])} style={Object.assign(styles.ul, { listStyleType: props.type }, props.style)} className={classnames('scuba-list', props.className)} > {props.children} </ul> ); export default List;
src/encoded/static/components/form.js
T2DREAM/t2dream-portal
/* eslint-disable jsx-a11y/label-has-for */ import React from 'react'; import PropTypes from 'prop-types'; import jsonschema from 'jsonschema'; import _ from 'underscore'; import offset from '../libs/offset'; import { FetchedData, Param } from './fetched'; import { parseAndLogError, listingTitles } from './globals'; import { FileInput, ItemPreview, ObjectPicker } from './inputs'; import Layout from './layout'; import DropdownButton from '../libs/bootstrap/button'; import { DropdownMenu } from '../libs/bootstrap/dropdown-menu'; const validator = new jsonschema.Validator(); // Add validator for regex patterns in our schemas validator.attributes.pattern = function validatePattern(instance, schema) { let error; if (typeof instance === 'string') { if (typeof schema.pattern !== 'string') throw new jsonschema.SchemaError('"pattern" expects a string', schema); if (!instance.match(schema.pattern)) { error = `does not match pattern ${JSON.stringify(schema.pattern)}`; } } return error; }; // Parse object and property from `linkFrom`. // Backrefs have a linkFrom property in the form // (object type).(property name) const parseLinkFrom = function parseLinkFrom(linkFrom) { const parts = linkFrom.split('.'); return { type: parts[0], prop: parts[1], }; }; // Validate `linkFrom` validator.attributes.linkFrom = function validateLinkFrom(instance, schema, options, ctx) { let result; if (instance !== undefined && instance instanceof Object) { const linkFrom = parseLinkFrom(schema.linkFrom); const types = instance['@type']; if (!_.contains(types, linkFrom.type)) { result = `expected object of type ${linkFrom.type}`; } const subschema = options.schemas[types[0]]; result = this.attributes.properties.call(this, instance, subschema, options, ctx); } return result; }; // Recursively filter an object to remove calculated properties // (`schema_version`). // This is used before sending the value to the server. const filterValue = function filterValue(value) { let result; if (Array.isArray(value)) { result = value.map(filterValue); } else if (typeof value === 'object') { result = {}; _.each(value, (v, k) => { if (k === '@type') { // We're not allowed to change an existing item's @type // but the server needs to know it for new items. if (!value['@id']) { result['@type'] = v; } } else if (k === 'layout') { // Avoid filtering out @type from layout blocks result[k] = v; } else if (k !== 'schema_version') { result[k] = filterValue(v); } }); } else { result = value; } return result; }; // Given a schema, construct a default object. // The default object includes the `default` value // for any property that defines one, // with the exception of read-only and non-submittable properties. const defaultValue = function defaultValue(schema) { if (schema.default !== undefined) { return schema.default !== undefined ? schema.default : undefined; } else if (schema.properties !== undefined) { const value = {}; _.each(schema.properties, (property, name) => { if (property.notSubmittable) return; if (!property.readonly) { const propertyDefault = defaultValue(property); if (propertyDefault !== undefined) { value[name] = propertyDefault; } } }); return (Object.keys(value).length ? value : undefined); } return schema.default || undefined; }; const UpdateChildMixin = superclass => class extends superclass { updateChild(name, subvalue) { // This is the workhorse for passing for field updates // up the hierarchy of form fields. // It constructs a new value for the current element // by replacing the value of one of its children, // then propagates the new value to its parent. const schema = this.props.schema; let oldValue = this.props.value; let newValue; if (schema.type === 'object') { // Clone the old value so we don't mutate it newValue = Object.assign({}, oldValue); // Set the new value unless it is undefined if (subvalue !== undefined) { newValue[name] = subvalue; } else if (newValue[name] !== undefined) { delete newValue[name]; } } else if (schema.type === 'array') { // Construct the old value using slices of the old // so we don't mutate it oldValue = oldValue || []; newValue = oldValue.slice(0, name).concat(subvalue).concat(oldValue.slice(name + 1)); } // Pass the new value to the parent this.props.updateChild(this.props.name, newValue); } }; class RepeatingItem extends React.Component { // A form field for editing one item in an array // (part of a RepeatingFieldset). // It delegates rendering the field to an actual Field component, // but also shows a button to remove the item. constructor() { super(); // Bind `this` to non-React methods. this.handleRemove = this.handleRemove.bind(this); this.updateChild = this.updateChild.bind(this); } handleRemove(e) { // Called when the remove button is clicked. e.preventDefault(); // eslint-disable-next-line no-alert if (!confirm('Are you sure you want to remove this item?')) { return; } if (this.props.onRemove) { this.props.onRemove(this.props.name); } } updateChild(name, value) { // When the contained field value is updated, // tell our parent RepeatingFieldset to update the correct index. this.props.updateChild(this.props.name, value); } render() { const { path, schema, value } = this.props; return ( <div className="rf-RepeatingFieldset__item"> <Field path={path} schema={schema} value={value} updateChild={this.updateChild} hideLabel /> {!this.context.readonly ? <button onClick={this.handleRemove} type="button" className="rf-RepeatingFieldset__remove" >&times;</button> : ''} </div> ); } } RepeatingItem.propTypes = { name: PropTypes.number, path: PropTypes.string, schema: PropTypes.object, onRemove: PropTypes.func, value: PropTypes.any, updateChild: PropTypes.func.isRequired, }; RepeatingItem.defaultProps = { name: '', path: '', schema: {}, onRemove: null, value: null, }; RepeatingItem.contextTypes = { readonly: PropTypes.bool, }; class RepeatingFieldset extends UpdateChildMixin(React.Component) { // A form field for editing an array. // Each item in the array is rendered via RepeatingItem. // Also shows a button to add a new item. constructor() { super(); // Counter which is incremented every time an item is removed. // This is used as part of the React key for contained RepeatingItems // to make sure that we re-render all items after one is removed. // After a removal the same array index may point to a different // item, so it's not safe to use the array index alone as the key. this.state = { generation: 0 }; // Bind `this` to non-React methods. this.onRemove = this.onRemove.bind(this); this.handleAdd = this.handleAdd.bind(this); this.updateChild = this.updateChild.bind(this); } onRemove(index) { // Called when a contained RepeatingItem is removed. // Remove the specified index from the current value. const oldValue = this.props.value; let value = oldValue.slice(0, index).concat(oldValue.slice(index + 1)); if (value.length === 0) { value = undefined; } // Increment `this.state.generation` (see explanation in getInitialState) this.setState({ generation: this.state.generation + 1 }); // Pass the new value for the entire array to parent this.props.updateChild(this.props.name, value); } handleAdd(e) { // Called when the add button is clicked. e.preventDefault(); const schema = this.props.schema; const subtype = e.target.getAttribute('data-subtype'); let newValue; if (subtype) { // Construct a child object. // It needs a reference back to the parent object. const subschema = this.context.schemas[subtype]; newValue = defaultValue(subschema); newValue['@type'] = [subtype]; const linkFrom = parseLinkFrom(schema.items.linkFrom); if (subschema.properties[linkFrom.prop].type === 'array') { newValue[linkFrom.prop] = [this.context.id]; } else { newValue[linkFrom.prop] = this.context.id; } } else { // Simple subitem; construct default value from schema; newValue = defaultValue(schema.items); } // Add the new subitem to the end of the array. const value = (this.props.value || []).concat(newValue); // Pass the new value for the entire array to parent this.props.updateChild(this.props.name, value); } render() { const { path, value, schema } = this.props; const schemas = this.context.schemas; const linkFrom = schema.items.linkFrom; const subtypes = linkFrom ? schemas._subtypes[parseLinkFrom(linkFrom).type] : []; let button = null; if (!this.context.readonly) { if (subtypes.length > 1) { button = ( <DropdownButton title="Add" buttonClasses="rf-RepeatingFieldset__add"> <DropdownMenu> {subtypes.map(subtype => <a href="#" key={subtype} data-subtype={subtype} onClick={this.handleAdd} >{schemas[subtype].title}</a>)} </DropdownMenu> </DropdownButton> ); } else { button = ( <button type="button" onClick={this.handleAdd} data-subtype={subtypes.length === 1 ? subtypes[0] : null} className="rf-RepeatingFieldset__add" >Add</button> ); } } return ( <div> <div className="rf-RepeatingFieldset__items"> {value ? value.map((subvalue, key) => { const props = { key: `${this.state.generation}.${key}`, name: key, path: `${path}.${key}`, value: subvalue, schema: schema.items, updateChild: this.updateChild, onRemove: this.onRemove, }; return <RepeatingItem {...props} />; }) : ''} </div> {button} </div> ); } } RepeatingFieldset.propTypes = { schema: PropTypes.object, name: PropTypes.string, path: PropTypes.string, value: PropTypes.any, updateChild: PropTypes.func, }; RepeatingFieldset.contextTypes = { schemas: PropTypes.object, readonly: PropTypes.bool, id: PropTypes.string, }; class ObjectField extends React.Component { // Wrapper to determine which schema to use for an object, // then render a Field with that schema. Used after ChildObject // fetches a child object from the server. render() { const type = this.props.value['@type'][0]; const schema = this.context.schemas[type]; return <Field {...this.props} schema={schema} />; } } ObjectField.propTypes = { value: PropTypes.any, }; ObjectField.defaultProps = { value: null, }; ObjectField.contextTypes = { schemas: PropTypes.object, }; class ChildObject extends React.Component { // A form field for editing a child object // (a subitem of an array property using linkFrom). // Initially the value is a URI and we render a preview of the object. // If the user expands the item we fetch its form frame and render form fields. // If the user updates any fields the new value is the updated object // rather than just the URI. constructor(props, context) { super(props); const value = this.props.value; const error = context.errors[this.props.path]; const url = typeof value === 'string' ? value : null; this.state = { url, // Start collapsed for existing children, // expanded when adding a new one or if there are errors collapsed: url && !error, }; // Bind `this` to non-React methods. this.toggleCollapsed = this.toggleCollapsed.bind(this); this.updateChild = this.updateChild.bind(this); } toggleCollapsed() { // Toggle collapsed state when collapsible trigger is clicked. this.setState({ collapsed: !this.state.collapsed }); } updateChild(name, value) { // Pass new value up to our parent. if (this.state.url) { value['@id'] = this.state.url; } this.props.updateChild(this.props.name, value); } render() { const { path, value } = this.props; let preview; let fieldset; if (this.state.url) { // We have a URI for an existing object. const previewUrl = this.state.url; // When collapsed, fetch the object and render it using ItemPreview. preview = ( <FetchedData> <Param name="data" url={previewUrl} /> <ItemPreview /> </FetchedData> ); // When expanded, fetch the form frame and render form fields. if (typeof value === 'string') { fieldset = ( <FetchedData> <Param name="value" url={`${this.state.url}?frame=form`} /> <ObjectField path={path} updateChild={this.updateChild} /> </FetchedData> ); } else { fieldset = <ObjectField path={path} value={value} updateChild={this.updateChild} />; } } else { // We don't have a URI yet (it's a new object). // When collapsed, render a placeholder. const schema = this.context.schemas[value['@type'][0]]; preview = ( <ul className="nav result-table"> <li> <div className="accession">{`New ${schema.title}`}</div> </li> </ul> ); // When expanded, render form fields (but there's no form frame to fetch) fieldset = (<ObjectField path={path} value={value} updateChild={this.updateChild} />); } return ( <div className="collapsible"> <button type="button" className="collapsible-trigger" onClick={this.toggleCollapsed} >{this.state.collapsed ? '▶ ' : '▼ '}</button> {this.state.collapsed ? preview : fieldset} </div> ); } } ChildObject.propTypes = { name: PropTypes.any, path: PropTypes.string, value: PropTypes.any, updateChild: PropTypes.func.isRequired, }; ChildObject.defaultProps = { name: null, path: '', value: null, }; ChildObject.contextTypes = { schemas: PropTypes.object, errors: PropTypes.object, }; ChildObject.childContextTypes = { id: PropTypes.string, }; export class Field extends UpdateChildMixin(React.Component) { // Build form input components based on a JSON schema // (or a portion thereof). // An entire form is comprised of a hierarchy of Field components; // each field propagates updates to its parent (via the `updateChild` prop) // until it reaches the Form itself. // For each field we render a label (from the schema `title` and `description`), // any validation error messages, and the input itself. // The Field determines what kind of input to render based on the schema: // - `type: 'object'`: Renders a separate sub-Field for each object property // except `uuid`, `schema_version`, and computed properties. // - `type: 'array'`: Renders using `RepeatingFieldset`. // - `type: 'boolean'`: Renders an HTML checkbox `input` element. // - `type: 'integer' or 'number'`: Renders an HTML number `input` elemtn. // - schema with `enum`: Renders an HTML `select` element. // - schema with `linkTo`: Renders an `ObjectPicker` for searching and selecting other objects. // - schema with `linkFrom`: Renders using `ChildObject`. // - schema with `formInput: 'file'`: Renders a `FileInput` to handle file uploads. // - schema with `formInput: 'textarea`: Renders an HTML `textarea` element. // - schema with `formInput: 'layout'`: Renders a `Layout` for drag-and-drop placement of content blocks. // - anything else with `type: 'string'`: Renders an HTML text `input` element. // - Custom form inputs for particular properties can be specified in the schema's `formInput` property. // If the schema (or the schema for any parent field) has `readonly: true`, // the input is disabled and the field value cannot be edited. constructor() { super(); // Set intial React state. this.state = { isDirty: false }; // Bind `this` to non-React methods. this.handleChange = this.handleChange.bind(this); this.updateChild = this.updateChild.bind(this); } getChildContext() { // Allow contained fields to tell whether they are inside a readonly field. return { readonly: !!(this.context.readonly || this.props.schema.readonly) }; } // Don't update when state is changed. // (Without this, the update to isDirty from handleChange causes // the input to re-render before the new value prop has propagated // from the parent, causing the cursor position to be lost. // See https://github.com/facebook/react/issues/955) // This should be safe as long as Field's state only contains isDirty. shouldComponentUpdate(nextProps) { return nextProps !== this.props; } handleChange(e) { // Handles change events on (leaf) input elements. let value; if (e && e.target) { // We were passed an event; get the value from its target. if (e.target.type === 'checkbox') { value = e.target.checked; } else { value = e.target.value; } } else { // We were passed the value itself, not an event. value = e; } // Remove empty and null values so they won't pass validation for required fields. if (value === null || value === '') { value = undefined; } const type = this.props.schema.type; if (value && (type === 'integer' || type === 'number')) { try { value = parseFloat(value); } catch (err) { // Keep string, which should fail schema validation } } // Record that this field was modified. this.setState({ isDirty: true }); // Pass the new value to the parent. this.props.updateChild(this.props.name, value); } render() { const { name, path, schema, value } = this.props; // FIXME Redmine #3413 if (schema === undefined) { return null; } const errors = this.context.errors; const isValid = !errors[path]; const type = schema.type || 'string'; let classBase = 'rf-Field'; if (type === 'object') { classBase = 'rf-Fieldset'; } else if (type === 'array') { classBase = 'rf-RepeatingFieldset'; } let className = this.props.className; const readonly = this.context.readonly || schema.readonly; const inputProps = { name, value, onChange: this.handleChange, disabled: readonly, }; let input = schema.formInput; if (input) { if (input === 'file') { input = <FileInput {...inputProps} />; } else if (input === 'textarea') { input = <textarea rows="4" {...inputProps} />; } else if (input === 'layout') { input = <Layout {...inputProps} editable={!readonly} />; } else { // We were passed an arbitrary custom input, // which we need to clone to specify the correct props. input = React.cloneElement(input, inputProps); } } else if (schema.linkFrom) { input = (<ChildObject name={this.props.name} path={path} schema={schema} value={value} updateChild={this.props.updateChild} />); } else if (type === 'object') { input = []; Object.keys(schema.properties).forEach((key) => { if (key === 'uuid' || key === 'schema_version') return; const subschema = schema.properties[key]; if (subschema.notSubmittable || subschema.hideFromForms) return; // Readonly fields are omitted when showReadOnly is false // (i.e. when adding a new object). if (!this.context.showReadOnly && subschema.readonly) return; // we can only edit child objects if we know the current object's id if (subschema.items && subschema.items.linkFrom && !this.context.id) return; const required = _.contains((schema.required || []), key); input.push(<Field key={key} name={key} path={`${path}.${key}`} schema={subschema} value={value && value[key]} updateChild={this.updateChild} className={required ? 'required' : ''} />); }); } else if (type === 'array') { input = (<RepeatingFieldset name={this.props.name} path={path} schema={schema} value={value} updateChild={this.props.updateChild} />); } else if (schema.enum) { let options = schema.enum.map(v => <option key={v} value={v}>{v}</option>); if (!schema.default) { // "_null_" is a placeholder; it'd be nice if we could actually use null // to avoid potential collision with real options, but it's not a valid // React key. options = [<option key="_null_" value={null} />].concat(options); } input = <select className="form-control" {...inputProps}>{options}</select>; } else if (schema.linkTo) { // Restrict ObjectPicker to finding the specified type // FIXME this should handle an array of types too const restrictions = { type: [schema.linkTo] }; input = (<ObjectPicker {...inputProps} searchBase={`?mode=picker&type=${schema.linkTo}`} restrictions={restrictions} />); } else if (schema.type === 'boolean') { input = <input type="checkbox" {...inputProps} />; } else if (schema.type === 'integer' || schema.type === 'number') { input = <input type="number" {...inputProps} />; } else { input = <input type="text" {...inputProps} value={value || ''} />; } // Provide a CSS hook to indicate fields with errors if (!isValid) { className = `${className} ${classBase}--invalid`; } return ( <div className={`${classBase} ${className}`}> {!this.props.hideLabel ? <label className={`${classBase}__label rf-Label`}> <span className="rf-Label__label">{schema.title}</span> <span className="rf-Hint">{schema.description}</span> </label> : ''} {(this.context.submitted || this.state.isDirty) && errors[path] ? <span className="rf-Message">{errors[path]}</span> : ''} {input} </div> ); } } Field.propTypes = { name: PropTypes.any, path: PropTypes.string, schema: PropTypes.object, value: PropTypes.any, className: PropTypes.string, updateChild: PropTypes.func.isRequired, hideLabel: PropTypes.bool, }; Field.defaultProps = { name: '', path: 'instance', schema: null, value: '', hideLabel: false, className: '', }; Field.contextTypes = { submitted: PropTypes.bool, errors: PropTypes.object, showReadOnly: PropTypes.bool, readonly: PropTypes.bool, id: PropTypes.string, }; Field.childContextTypes = { readonly: PropTypes.bool, }; export class Form extends React.Component { // The Form component renders a form based on a JSON schema. // It renders an actual HTML `form` element which contains // form fields (via the `Field` component) // and Cancel and Save buttons. // The initial form value is taken from the `defaultValue` prop. // The JSON schema is specified in the `schema` prop. // As the form is edited, validation against the schema // is performed (on the client side) and errors are reported. // Once the form has been edited, the user must confirm a dialog // to navigate away from the form. // The Save button is enabled if the form has been edited // and input is valid. Submitting the form // (by hitting Enter or clicking the Save button) // serializes the form value to JSON and sends it to the // server endpoint specified in the `action` and `method` // props. // If saving was successful, the form's `onFinish` prop // is called. Otherwise, it renders error messages // (either formwide errors below the save button // or field-specific errors in the context of the field) // and scrolls to the first one. // Clicking the Cancel button returns to the homepage. constructor(props) { super(props); // Set initial React state. this.state = { isDirty: false, isValid: true, value: this.props.defaultValue, errors: {}, submitted: false, }; // Bind `this` to non-React methods. this.validate = this.validate.bind(this); this.update = this.update.bind(this); this.canSave = this.canSave.bind(this); this.save = this.save.bind(this); this.receive = this.receive.bind(this); this.showErrors = this.showErrors.bind(this); this.finish = this.finish.bind(this); } getChildContext() { // Provide various props to contained fields via React's // `context` mechanism to avoid needing to explicitly // pass them through multiple layers of nested components. return { schemas: this.props.schemas, canSave: this.canSave, onTriggerSave: this.save, errors: this.state.errors, showReadOnly: this.props.showReadOnly, id: this.props.id, submitted: this.state.submitted, }; } componentDidUpdate(prevProps, prevState) { // If form error state changed, scroll to first error message // to make sure the user notices it. if (!_.isEqual(prevState.errors, this.state.errors) || (this.state.message && (this.state.message !== prevState.message))) { const message = document.querySelector('.rf-Message,.alert'); if (message) { window.scrollTo(0, offset(message).top - document.getElementById('navbar').clientHeight); } } } validate(value) { // Get validation errors from jsonschema validator. const validation = validator.validate(value, this.props.schema, { schemas: this.props.schemas, // Don't validate `dependencies` in schema, // because the errors don't get reported at the correct path. // These should still be reported by server-side validation on form submit. skipAttributes: ['dependencies'], }); // `jsonschema` uses field paths like // `instance.aliases[0]` // but we use paths like // `instance.aliases.0` // so we have to convert them here. validation.errorsByPath = {}; const errorsByPath = validation.errorsByPath; validation.errors.forEach((error) => { let path = error.property.replace(/\[/g, '.').replace(/]/g, ''); // Missing values for required properties are reported // on the parent property (the one that lists it as required) // so we have to append the error's `argument` // to make sure we show the missing value // in the most helpful place (next to the empty input). if (error.name === 'required') { path = `${path}.${error.argument}`; } errorsByPath[path] = error.message; }); return validation; } update(name, value) { // Called whenever the form value was changed. // (The `name` arg is ignored; most Field components have a // name and pass it when propagating an update // to their parent via the `updateChild` prop, // but the top-level Field does not have a name.) // for debugging: // console.log(value); // Update validation state. const validation = this.validate(value); const nextState = { value, isDirty: true, isValid: validation.valid, errors: validation.errorsByPath, }; // Notify app that the page is dirty and we should // show a confirmation dialog before allowing navigation. if (!this.state.unsavedToken) { nextState.unsavedToken = this.context.adviseUnsavedChanges(); } this.setState(nextState); } canSave() { // Called to determine whether to enable the Save button or not. // It is enabled if the form has been edited, the value is valid // according to the schema, and the form submission is not in progress. return this.state.isDirty && this.state.isValid && !this.state.editor_error && !this.communicating; } save(e) { // Send the form value to the server. // Avoid non-AJAX submission of form. e.preventDefault(); e.stopPropagation(); const button = e.target.getAttribute('data-button'); // Filter out `schema_version` property const value = filterValue(this.state.value); // Make the request const { method, action, etag } = this.props; const request = this.context.fetch(action, { method, headers: { 'If-Match': etag || '*', Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(value), }); // Handle errors using `parseAndLogError`; // otherwise convert response to JSON and pass it to `this.receive` request.then((response) => { if (!response.ok) throw response; return response.json(); }) .catch(parseAndLogError.bind(undefined, 'putRequest')) .then(this.receive.bind(this, button)); // Set `communicating` to true so the Save button becomes disabled. this.setState({ message: null, error: null, communicating: true, putRequest: request, }); } receive(button, data) { // Handle a response that is not an HTTP error status. // Handle server-side validation errors using `this.showErrors`. const erred = (data['@type'] || []).indexOf('Error') > -1; if (erred) { return this.showErrors(data); } // Handle a successful form submission using `this.finish`. return this.finish(button, data); } showErrors(data) { // Translate server-side validation errors. // The Field component uses paths like // `instance.aliases.0` // but the server gives us paths like // `['aliases', 0]` // so we have to translate here. const errors = {}; let error; if (data.errors !== undefined) { data.errors.forEach((err) => { let path = `instance${err.name.length ? `.${err.name.join('.')}` : ''}`; // Missing values for required properties are reported // on the parent property (the one that specifies `required`) // so we have to add the property that is actually missing here. const match = /^u?'([^']+)' is a required property$/.exec(err.description); if (match) { path = `${path}.${match[1]}`; } errors[path] = err.description; }); } else if (data.description) { // This is a form-wide error rather than a field-specific one. error = `${data.description} ${data.detail || ''}`; } // First clear errors to make sure componentDidUpdate // will decide we need to scroll again even if the // errors are the same as the last attempted submission. this.setState({ errors: {} }); this.setState({ data, error, errors, submitted: true, communicating: false, }); } finish(button, data) { // Handle a successful form submission. // Let the app know navigation is now allowed again // without showing a confirmation dialog // (i.e. the form is no longer dirty) if (this.state.unsavedToken) { this.state.unsavedToken.release(); this.setState({ unsavedToken: null }); } if (button === 'saveAndAdd') { const context = data['@graph'][0]; const title = listingTitles.lookup(context)({ context }); let message = `Created ${title}`; if (context.accession && context.accession !== title) { message += ` with accession ${context.accession}`; } message += '.'; this.setState({ message }); } else if (this.props.onFinish) { // Default action: defer to the `onFinish` prop. this.props.onFinish(data); } } render() { return ( <form className="rf-Form" onSubmit={this.save} > {this.state.message ? <div className="alert alert-success">{this.state.message}</div> : ''} <Field schema={this.props.schema} value={this.state.value} updateChild={this.update} /> <div className="pull-right"> <a href="" className="btn btn-default">Cancel</a> {' '} <button className="btn btn-success" onClick={this.save} disabled={!this.canSave()} >{this.props.submitLabel}</button> {' '} {this.props.showSaveAndAdd ? <button data-button="saveAndAdd" className="btn btn-success" onClick={this.save} disabled={!this.canSave()} >Save & Add Another</button> : ''} </div> {this.state.error ? <div className="alert alert-danger">{this.state.error}</div> : ''} </form> ); } } Form.propTypes = { defaultValue: PropTypes.any, schemas: PropTypes.object, schema: PropTypes.object.isRequired, showReadOnly: PropTypes.bool, showSaveAndAdd: PropTypes.bool, id: PropTypes.string, method: PropTypes.string.isRequired, action: PropTypes.string.isRequired, etag: PropTypes.string, onFinish: PropTypes.func.isRequired, submitLabel: PropTypes.string, }; Form.defaultProps = { defaultValue: null, schemas: null, id: '', etag: '', showReadOnly: true, showSaveAndAdd: false, submitLabel: 'Save', }; Form.contextTypes = { adviseUnsavedChanges: PropTypes.func, fetch: PropTypes.func, }; Form.childContextTypes = { schemas: PropTypes.object, canSave: PropTypes.func, onTriggerSave: PropTypes.func, errors: PropTypes.object, showReadOnly: PropTypes.bool, id: PropTypes.string, submitted: PropTypes.bool, }; export class JSONSchemaForm extends React.Component { // JSONSchemaForm is a wrapper of Form // that is used from the ItemEdit component after // it fetches the `schemas` and the `context` // (which is the edit frame of the object being edited). // It exists to: // 1. Look up a specific type schema within the full schemas object. // 2. Construct a default value, based on the schema, // if we're adding a new object. // Other properties are passed through to the Form. constructor(props) { super(props); const { type, schemas } = this.props; this.state = { schema: schemas[type], value: this.props.context || defaultValue(schemas[type]), }; } render() { return (<Form action={this.props.action} method={this.props.method} etag={this.props.etag} schemas={this.props.schemas} schema={this.state.schema} defaultValue={this.state.value} showReadOnly={this.props.showReadOnly} showSaveAndAdd={this.props.showSaveAndAdd} id={this.props.id} onFinish={this.props.onFinish} />); } } JSONSchemaForm.propTypes = { type: PropTypes.string.isRequired, schemas: PropTypes.object, context: PropTypes.any, action: PropTypes.string.isRequired, method: PropTypes.string.isRequired, etag: PropTypes.string, showReadOnly: PropTypes.bool, showSaveAndAdd: PropTypes.bool, id: PropTypes.string, onFinish: PropTypes.func.isRequired, }; JSONSchemaForm.defaultProps = { schemas: null, context: null, id: null, etag: '', showReadOnly: true, showSaveAndAdd: false, };
app/components/Settings.js
alfg/somafm
import React, { Component } from 'react'; import Nav from './common/Nav'; import SideNav from './common/SideNav'; import styles from './Settings.module.css'; export default class Settings extends Component { static propTypes = { }; constructor(props) { super(props); this.state = { }; } render() { return ( <div className={styles.settings}> <SideNav /> <div className={styles.container}> <Nav /> <h2>Settings</h2> </div> </div> ); } }
basics/lib/root-component.js
zpratt/react-tdd-guide
import React from 'react'; import {PropTypes} from 'prop-types'; function Root(props) { const { users } = props; return ( <ul> {users.map((user, index) => <li key={index}>{user.name}</li>)} </ul> ); } Root.displayName = 'Root'; Root.propTypes = { users: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string })) }; export default Root;
app/containers/LocaleToggle/index.js
andyzeli/Bil
/* * * LanguageToggle * */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Toggle from 'components/Toggle'; import Wrapper from './Wrapper'; import messages from './messages'; import { appLocales } from '../../i18n'; import { changeLocale } from '../LanguageProvider/actions'; import { makeSelectLocale } from '../LanguageProvider/selectors'; export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <Wrapper> <Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} /> </Wrapper> ); } } LocaleToggle.propTypes = { onLocaleToggle: PropTypes.func, locale: PropTypes.string, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
client/components/ChooseUserName.js
GO345724/pair-programming
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import {Form, FormGroup, FormControl, Button, ControlLabel} from 'react-bootstrap'; class ChooseUserName extends Component { constructor(props) { super(props); this.state = { userName: '' } this.updateState = this.updateState.bind(this); this.triggerChooseUserName = this.triggerChooseUserName.bind(this); } updateState(event) { let userName = event.target.value; this.setState({userName}); } triggerChooseUserName(event) { event.preventDefault(); this.props.chooseUserName(this.state.userName); } render() { return( <div> <Form inline> <FormGroup controlId="formInlineUserName"> <FormControl type="text" defaultValue={this.props.userName} onChange={this.updateState}/> {' '} <Button type="submit" onClick={this.triggerChooseUserName} disabled={!this.state.userName}> Choose Username </Button> </FormGroup> </Form> </div> ) } } ChooseUserName.propTypes = { userName: PropTypes.string.isRequired, chooseUserName: PropTypes.func.isRequired } export default ChooseUserName;
components/animalNeighbourScene.js
marxsk/zobro
import React from 'react'; import { View, Text, ListView, TouchableHighlight, Alert, Image, } from 'react-native'; import * as scenes from '../scenes'; import styles from '../styles/styles'; import animals from '../animals'; var navigator; class Cell extends React.Component { constructor(props) { super(props); } render() { const animal = animals[this.props.item.animal]; const direction = this.props.item.direction; let directionArrow = null; if (direction === 'front') { directionArrow = require('../images/icon/arrow-front.png'); } else if (direction === 'back') { directionArrow = require('../images/icon/arrow-back.png'); } else if (direction === 'right') { directionArrow = require('../images/icon/arrow-right.png'); } else if (direction === 'left') { directionArrow = require('../images/icon/arrow-left.png'); } if ((animal === undefined) || (! 'name' in animal)) { return null; } return ( <TouchableHighlight onPress={() => scenes.navigatePush(navigator, scenes.ANIMAL_DETAIL, {animal: this.props.item.animal})} underlayColor='#bbbbbb' > <View style={[styles.eventItem, {flex: 1, flexDirection: 'row', alignItems: 'center', backgroundColor: this.props.backgroundColor}]}> <Image style={{height: 50, width: 50, marginRight: 10}} source={directionArrow} resizeMode='contain' /> <Text style={styles.eventItemText}>{animal.name}</Text> </View> </TouchableHighlight> ); } } export default class AnimalNeighbourScene extends React.Component { constructor(props) { super(props); navigator = this.props.navigator; const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows( animals[this.props.animal].neighbours.map(function(v) { return v }) )}; } componentWillMount() { this.props.bg(); } render() { const backgroundColors = [ '#37af54', '#2d9946', '#267f3b', '#20642f', '#0b2611', '#20642f', '#267f3b', '#2d9946', ]; let counter = 0; return ( <ListView dataSource={this.state.dataSource} renderRow={(data) => { let backgroundColor = backgroundColors[counter % backgroundColors.length]; counter++; return (<Cell item={data} backgroundColor = {backgroundColor} />); }} /> ); } } AnimalNeighbourScene.propTypes = { bg: React.PropTypes.func.isRequired, animal: React.PropTypes.string.isRequired, navigator: React.PropTypes.object.isRequired, };
src/svg-icons/navigation/more-vert.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationMoreVert = (props) => ( <SvgIcon {...props}> <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); NavigationMoreVert = pure(NavigationMoreVert); NavigationMoreVert.displayName = 'NavigationMoreVert'; NavigationMoreVert.muiName = 'SvgIcon'; export default NavigationMoreVert;
src/views/ArticleMain.js
fightingm/blog
import React from 'react'; import Markdown from 'react-markdown'; import ArticleData from './ArticleData'; import $ from 'jquery'; import hljs from 'highlight.js'; require ('../css/ArticleMain.css'); require ('highlight.js/styles/solarized-light.css'); export default class ArticleMain extends React.Component{ constructor() { super(); this.article=ArticleData; } componentWillMount() { let location=window.location.hash; let re=/(\d+)-(\d+)-(\d+)/g; let newstr=re.exec(location); this.year=newstr[1]; this.month=newstr[2]; this.day=newstr[3]; let newYear=ArticleData.filter(function(item){ return item.year == this.year; }.bind(this)); let newMonth=newYear[0].monthes.filter(function(item){ return item.month == this.month; }.bind(this)); this.newDay=newMonth[0].days.filter(function(item){ return item.day == this.day; }.bind(this))[0]; } componentDidMount() { //hljs.initHighlightingOnLoad(); hljs.configure({ tabReplace: ' ' }); //hljs.initHighlighting(); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); } render() { return ( <main className="ArticleMain main-body"> <article className="container"> <div id="article-con" className="article-con result-pane"> <Markdown source={this.newDay.con} skipHtml={false} escapeHtml={false} /> </div> <time className="write-t blue">{this.year}年{this.month}月{this.day}日</time> </article> </main> ); } }
src/js/components/App.js
designcreative/react-redux-template
import React, { Component } from 'react'; import ItemList from '../containers/item-list'; import ItemDetail from '../containers/item-detail'; require('../../scss/main.scss'); class App extends Component { render() { return ( <div> <h2>Item List</h2> <ItemList /> <hr/> <h2>Item Detail</h2> <ItemDetail /> </div> ); } } export default App;
docs/src/app/components/pages/components/DatePicker/ExampleToggle.js
hai-cea/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; import Toggle from 'material-ui/Toggle'; const optionsStyle = { maxWidth: 255, marginRight: 'auto', }; /** * This example allows you to set a date range, and to toggle `autoOk`, and `disableYearSelection`. */ export default class DatePickerExampleToggle extends React.Component { constructor(props) { super(props); const minDate = new Date(); const maxDate = new Date(); minDate.setFullYear(minDate.getFullYear() - 1); minDate.setHours(0, 0, 0, 0); maxDate.setFullYear(maxDate.getFullYear() + 1); maxDate.setHours(0, 0, 0, 0); this.state = { minDate: minDate, maxDate: maxDate, autoOk: false, disableYearSelection: false, }; } handleChangeMinDate = (event, date) => { this.setState({ minDate: date, }); }; handleChangeMaxDate = (event, date) => { this.setState({ maxDate: date, }); }; handleToggle = (event, toggled) => { this.setState({ [event.target.name]: toggled, }); }; render() { return ( <div> <DatePicker floatingLabelText="Ranged Date Picker" autoOk={this.state.autoOk} minDate={this.state.minDate} maxDate={this.state.maxDate} disableYearSelection={this.state.disableYearSelection} /> <div style={optionsStyle}> <DatePicker onChange={this.handleChangeMinDate} autoOk={this.state.autoOk} floatingLabelText="Min Date" defaultDate={this.state.minDate} disableYearSelection={this.state.disableYearSelection} /> <DatePicker onChange={this.handleChangeMaxDate} autoOk={this.state.autoOk} floatingLabelText="Max Date" defaultDate={this.state.maxDate} disableYearSelection={this.state.disableYearSelection} /> <Toggle name="autoOk" value="autoOk" label="Auto Ok" toggled={this.state.autoOk} onToggle={this.handleToggle} /> <Toggle name="disableYearSelection" value="disableYearSelection" label="Disable Year Selection" toggled={this.state.disableYearSelection} onToggle={this.handleToggle} /> </div> </div> ); } }