path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/Hello/Hello.js
kashjs/muszoo-react
import React from 'react'; export class Hello extends React.Component { render() { return <h1>Hello React! yey</h1>; } }
app/javascript/mastodon/features/hashtag_timeline/components/column_settings.js
ikuradon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Toggle from 'react-toggle'; import AsyncSelect from 'react-select/async'; import { NonceProvider } from 'react-select'; import SettingToggle from '../../notifications/components/setting_toggle'; const messages = defineMessages({ placeholder: { id: 'hashtag.column_settings.select.placeholder', defaultMessage: 'Enter hashtags…' }, noOptions: { id: 'hashtag.column_settings.select.no_options_message', defaultMessage: 'No suggestions found' }, }); export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, onLoad: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: this.hasTags(), }; hasTags () { return ['all', 'any', 'none'].map(mode => this.tags(mode).length > 0).includes(true); } tags (mode) { let tags = this.props.settings.getIn(['tags', mode]) || []; if (tags.toJSON) { return tags.toJSON(); } else { return tags; } }; onSelect = mode => value => this.props.onChange(['tags', mode], value); onToggle = () => { if (this.state.open && this.hasTags()) { this.props.onChange('tags', {}); } this.setState({ open: !this.state.open }); }; noOptionsMessage = () => this.props.intl.formatMessage(messages.noOptions); modeSelect (mode) { return ( <div className='column-settings__row'> <span className='column-settings__section'> {this.modeLabel(mode)} </span> <NonceProvider nonce={document.querySelector('meta[name=style-nonce]').content} cacheKey='tags'> <AsyncSelect isMulti autoFocus value={this.tags(mode)} onChange={this.onSelect(mode)} loadOptions={this.props.onLoad} className='column-select__container' classNamePrefix='column-select' name='tags' placeholder={this.props.intl.formatMessage(messages.placeholder)} noOptionsMessage={this.noOptionsMessage} /> </NonceProvider> </div> ); } modeLabel (mode) { switch(mode) { case 'any': return <FormattedMessage id='hashtag.column_settings.tag_mode.any' defaultMessage='Any of these' />; case 'all': return <FormattedMessage id='hashtag.column_settings.tag_mode.all' defaultMessage='All of these' />; case 'none': return <FormattedMessage id='hashtag.column_settings.tag_mode.none' defaultMessage='None of these' />; default: return ''; } }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <div className='setting-toggle'> <Toggle id='hashtag.column_settings.tag_toggle' onChange={this.onToggle} checked={this.state.open} /> <span className='setting-toggle__label'> <FormattedMessage id='hashtag.column_settings.tag_toggle' defaultMessage='Include additional tags in this column' /> </span> </div> </div> {this.state.open && ( <div className='column-settings__hashtags'> {this.modeSelect('any')} {this.modeSelect('all')} {this.modeSelect('none')} </div> )} <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['local']} onChange={onChange} label={<FormattedMessage id='community.column_settings.local_only' defaultMessage='Local only' />} /> </div> </div> ); } }
app/components/elements/TimeAgoWrapper.js
enisey14/platform
/* eslint react/prop-types: 0 */ import React from 'react'; import { FormattedRelative } from 'react-intl'; export default class TimeAgoWrapper extends React.Component { render() { let {date} = this.props if(date && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$/.test(date)) { date = date + 'Z' // Firefox really wants this Z (Zulu) } return <FormattedRelative {...this.props} value={date} /> } }
ui/src/components/IssueProviderList/index.js
denniss17/status-dashboard
import React, { Component } from 'react'; import IssueProvider from './IssueProvider'; import PropTypes from 'prop-types'; class IssueProviderList extends Component { render() { const { issueProviders, statusesForIssues } = this.props; return ( <div> {issueProviders && Object.keys(issueProviders).map(id => <IssueProvider key={id} issueProvider={issueProviders[id]} statusesForIssues={statusesForIssues}/>)} </div> ); } } IssueProviderList.propTypes = { issueProviders: PropTypes.object, statusesForIssues: PropTypes.object }; export default IssueProviderList;
app/config/routes.js
cshutchinson/sk
import React, { Component } from 'react'; import Main from '../components/Main'; import Home from '../components/Home'; import { Router, Route, IndexRoute, Link } from 'react-router' module.exports = ( <Route path="/" component={Main}> <IndexRoute component={Home} /> </Route> );
packages/react-static/src/browser/components/SiteData.js
nozzle/react-static
import React from 'react' import useSiteData from '../hooks/useSiteData' export function SiteData({ children }) { return children(useSiteData()) } export function withSiteData(Comp) { return function componentWithSiteData(props) { const routeData = useSiteData() return <Comp {...props} {...routeData} /> } }
src/components/common/Button.js
amir5000/react-native-manager-app
import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; const Button = ({ onPress, children }) => { const { buttonStyle, buttonTextStyle } = styles; return ( <TouchableOpacity onPress={onPress} style={buttonStyle}> <Text style={buttonTextStyle}>{children}</Text> </TouchableOpacity> ); }; const styles = { buttonStyle: { flex: 1, alignSelf: 'stretch', backgroundColor: '#FFF', borderRadius: 5, borderWidth: 1, borderColor: '#007AFF', marginLeft: 5, marginRight: 5 }, buttonTextStyle: { alignSelf: 'center', color: '#007AFF', fontWeight: '600', paddingTop: 10, paddingBottom: 10 } }; export { Button };
packages/material-ui-icons/src/ArrowForward.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ArrowForward = props => <SvgIcon {...props}> <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" /> </SvgIcon>; ArrowForward = pure(ArrowForward); ArrowForward.muiName = 'SvgIcon'; export default ArrowForward;
src/svg-icons/notification/folder-special.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationFolderSpecial = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-2.06 11L15 15.28 12.06 17l.78-3.33-2.59-2.24 3.41-.29L15 8l1.34 3.14 3.41.29-2.59 2.24.78 3.33z"/> </SvgIcon> ); NotificationFolderSpecial = pure(NotificationFolderSpecial); NotificationFolderSpecial.displayName = 'NotificationFolderSpecial'; NotificationFolderSpecial.muiName = 'SvgIcon'; export default NotificationFolderSpecial;
client/android/app/src/pages/SignUp.js
blusclips/zonaster
import React, { Component } from 'react'; import {Image, StyleSheet, AsyncStorage} from 'react-native'; import { StackNavigator } from 'react-navigation'; import { Container, Content, Text, H1, H3, Button, Item, Input, Grid, Col} from 'native-base'; import general from '../styles/general'; import Icon from 'react-native-vector-icons/FontAwesome'; import SplashScreen from 'react-native-splash-screen'; import { SocialIcon } from 'react-native-elements'; import progressDialog from '../../../../src/progressDialog.js'; import {action, observable} from 'mobx'; import {observer} from 'mobx-react/native'; import {autobind} from 'core-decorators'; @observer @autobind export default class SignUpScreen extends Component { static navigationOptions = { header:null }; constructor(props) { super(props); this.state = {error:'', email:'', password:'', re_password:''}; this.store = this.props.screenProps.store; this.createAccount = this.createAccount.bind(this); changeState = (text) =>{ this.setState({error:text}); } } createAccount = () =>{ this.store.isError = ""; let email = this.state.email; let pass = this.state.password; let re_pass = this.state.re_password; let fullnames = ""; if (email !== "") { if (pass !== "" && pass == re_pass) { progressDialog.show("Creating account, Please wait."); this.store.createAccount(this.props.navigation, email, pass, fullnames); }else{ this.store.isError = "Passwords don't match.."; } }else{ this.store.isError = "Enter Email address or Phone Number"; } } render(){ const { navigate } = this.props.navigation; return( <Container style={{backgroundColor:'#fff'}}> <Content style={{padding:30}}> <H1 style={{textAlign:'center', marginTop:55, marginBottom:35, fontWeight:'bold', color:'#B71C1C'}}>Zonaster</H1> <Text style={{textAlign:'center', fontWeight:'bold', color:'#B71C1C'}}> { this.store.isError } </Text> <Item style={general.pad}> <Icon active name='user-circle' size={20} /> <Input placeholder='Email or Phone' onChangeText={(email) => this.setState({email})}/> </Item> <Item style={general.pad}> <Icon active name='lock' size={25} /> <Input placeholder='Password' onChangeText={(password) => this.setState({password})} /> </Item> <Item style={general.pad}> <Icon active name='lock' size={25} /> <Input placeholder='Re Enter Password' onChangeText={(re_password) => this.setState({re_password})}/> </Item> <Button full rounded style={general.pad, general.primaryColorDark} onPress={this.createAccount}> <Text>Create Account</Text> </Button> <Text style={{marginTop:35, marginBottom:50, textAlign:'center'}}> By creating an account, you agree to our terms of use and privacy policies. </Text> </Content> </Container> ) } }
docs/src/app/components/pages/components/SelectField/ExampleFloatingLabel.js
rhaedes/material-ui
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; const items = [ <MenuItem key={1} value={1} primaryText="Never" />, <MenuItem key={2} value={2} primaryText="Every Night" />, <MenuItem key={3} value={3} primaryText="Weeknights" />, <MenuItem key={4} value={4} primaryText="Weekends" />, <MenuItem key={5} value={5} primaryText="Weekly" />, ]; export default class SelectFieldExampleFloatingLabel extends React.Component { constructor(props) { super(props); this.state = {value: null}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <div> <SelectField value={this.state.value} onChange={this.handleChange} floatingLabelText="Floating Label Text" > {items} </SelectField> <br /> <SelectField value={this.state.value} onChange={this.handleChange} floatingLabelText="Styled Floating Label Text" floatingLabelStyle={{color: 'red'}} > {items} </SelectField> </div> ); } }
src/components/js/Contacts.js
ucev/chatroom
import React, { Component } from 'react'; import UserItem from './UserItem'; import MyAction from '../../state/action'; class Contacts extends Component { render() { var state = MyAction.getState(); var userid = state.userid; var users = state.users.filter((user) => { return user.id != userid; }); var users = users.map((user) => { return ( <UserItem key={user.id} user={user} history={this.props.history} /> ) }) return ( <div> <div>{users}</div> </div> ); } } export default Contacts;
source/src/components/App.js
mondalamit/mondalamit.github.io
import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
GreenGremlin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import tiniestCat from './assets/tiniest-cat.jpg'; export default () => ( <img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" /> );
src/hucha.web/test/helpers/shallowRenderHelper.js
jparaya/hucha
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
docs/src/PageFooter.js
nickuraltsev/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className="bs-docs-footer" role="contentinfo"> <div className="container"> <div className="bs-docs-social"> <ul className="bs-docs-social-buttons"> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true" width={95} height={20} title="Star on GitHub" /> </li> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true" width={92} height={20} title="Fork on GitHub" /> </li> <li> <iframe src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder="0" scrolling="no"> </iframe> </li> </ul> </div> <p>Code licensed under <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE" target="_blank">MIT</a>.</p> <ul className="bs-docs-footer-links muted"> <li>Currently v{version}</li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/">GitHub</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/issues?state=open">Issues</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/releases">Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
demo/src/demo-components/indicators.js
Strikersoft/striker-store
import React from 'react'; import { shape, func, string } from 'prop-types'; import { observer } from 'mobx-react'; const IndicatorComponent = observer(({ indicator, type }) => { if (indicator.get()) { return <span>({type})</span>; } return null; }); IndicatorComponent.propTypes = { indicator: shape({ get: func }).isRequired, type: string }; IndicatorComponent.defaultProps = { type: 'Loading' }; IndicatorComponent.displayName = 'StatusIndicator'; export default IndicatorComponent;
node_modules/react-router/es/MemoryRouter.js
AngeliaGong/AngeliaGong.github.io
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(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; } function _inherits(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; } import warning from 'warning'; import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createMemoryHistory'; import Router from './Router'; /** * The public API for a <Router> that stores location in memory. */ var MemoryRouter = function (_React$Component) { _inherits(MemoryRouter, _React$Component); function MemoryRouter() { var _temp, _this, _ret; _classCallCheck(this, MemoryRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } MemoryRouter.prototype.componentWillMount = function componentWillMount() { warning(!this.props.history, '<MemoryRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { MemoryRouter as Router }`.'); }; MemoryRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return MemoryRouter; }(React.Component); MemoryRouter.propTypes = { initialEntries: PropTypes.array, initialIndex: PropTypes.number, getUserConfirmation: PropTypes.func, keyLength: PropTypes.number, children: PropTypes.node }; export default MemoryRouter;
src/icons/ViewModuleIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class ViewModuleIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M8 22h10V10H8v12zm0 14h10V24H8v12zm12 0h10V24H20v12zm12 0h10V24H32v12zM20 22h10V10H20v12zm12-12v12h10V10H32z"/></svg>;} };
app/components/Button.js
RogerZZZZZ/widget_electron
import React from 'react' import { Component } from 'react' let assetsPrefix = process.env.DEV? '..': '.' class Button extends Component{ constructor(props){ super(props); let picName = (this.props.status === false || this.props.status === undefined? this.props.name: this.props.name+"-done"); this.state = { picName: assetsPrefix + "/assets/" + picName+ ".png", originName: this.props.name } } _hoverInListener(){ this.setState({ picName : assetsPrefix + "/assets/" + this.state.originName + "-on.png" }) } _hoverOutListener(){ this.setState({ picName: assetsPrefix + "/assets/" + this.state.originName + ".png" }) } _buttonClick(){ let picName; if(this.props.status){ picName = this.props.name }else{ picName = this.props.name + '-done'; } this.setState({ picName: assetsPrefix + "/assets/" + picName + ".png" }) this.props.buttonClick(); } render(){ return ( <div className={this.props.align == "left"? "left-button circle-button": "right-button circle-button"} onMouseOver={this.props.static?null:this._hoverInListener.bind(this)} onClick={this._buttonClick.bind(this)} onMouseLeave={this.props.static?null:this._hoverOutListener.bind(this)}> <img src={this.state.picName} className="circle-button-img" ref="buttonImg"/> </div> ) } } export default Button
tilapp/src/containers/Scenes/Capture/Index/index.js
tilap/tilapp
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import merge from 'deep-assign'; import { Container } from 'native-base'; import processBarcode from './services/processBarcode'; import { ReverseCameraIcon, ReverseCameraActiveIcon, FlashCameraIcon, FlashCameraActiveIcon } from '~/components/Icons'; import BarCodeScannerPlus from '~/components/BareCodeScannerPlus'; import SimpleMessage from '~/components/SimpleMessage/'; import { OfflineIcon } from '~/components/Icons/'; import NavigationButton from '~/components/NavigationButton'; class CaptureScene extends Component { handleBarCodeRead = async ({ data: barcode }) => { if (!this.props.scanEnabled) { return false; } const wordings = { start: this.props.wordingStartScanning, waiting: this.props.wordingSearchingWait, }; const book = await processBarcode({ ean: barcode, wordings }); if (book) { this.props.navigation.navigate('Book', { bookScreenType: 'sell' }); } } render() { if (!this.props.connected) { return ( <SimpleMessage Icon={OfflineIcon} text="You need to be connected to Internet to add a book." /> ); } return this.props.displayScanner ? ( <Container> <BarCodeScannerPlus onBarCodeRead={this.handleBarCodeRead} adviseText={this.props.scanEnabled ? "Scan a book bar code" : "Scanner disabled"} paused={!this.props.scanEnabled} IconReverseCamera={ReverseCameraIcon} IconReverseCameraActive={ReverseCameraActiveIcon} IconFlashCamera={FlashCameraIcon} IconFlashCameraActive={FlashCameraActiveIcon} /> </Container> ) : null; } } CaptureScene.propTypes = { navigation: PropTypes.any.isRequired, scanEnabled: PropTypes.bool.isRequired, displayScanner: PropTypes.bool.isRequired, scannerEnabled: PropTypes.bool.isRequired, wordingStartScanning: PropTypes.string, wordingSearchingWait: PropTypes.arrayOf(PropTypes.string), connected: PropTypes.bool.isRequired, }; CaptureScene.defaultProps = { wordingStartScanning: 'Analyzing the barcode...', wordingSearchingWait: [ 'Searching the book...', 'You are the first one looking for this book...', 'We are digging to find that book...', 'Seems it is not a common book hu?', ], }; CaptureScene.navigationOptions = (props) => { console.log(props.navigationOptions) return merge({}, (props.navigationOptions || {}), { title: 'Add a book', headerRight: ( <NavigationButton icon="help" onPress={() => props.navigation.navigate('CaptureHelp')} /> ), }); } const mapStateToProps = ({ scenes: { barcodescanner: { enabled } }, services: { navigation: { current }, api: { connected }, }, }) => ({ scanEnabled: enabled, displayScanner: current.startsWith('Capture'), scannerEnabled: current === 'CaptureIndex', connected, }); export default connect(mapStateToProps)(CaptureScene);
src/modules/settings/components/Feedback.js
CaronaBoard/caronaboard-native
import React from 'react' import { WebView } from 'react-native' export const Feedback = () => { return ( <WebView source={{uri: 'https://goo.gl/forms/IxVqYmchYVrHkNLq2'}} style={{flex: 1}} /> ) }
packages/benchmarks-utils/src/index.js
A-gambit/CSS-IN-JS-Benchmarks
import React from 'react'; function getTable(max = 30) { let table = []; for (let i = 0; i < max; i++) { table[i] = [1]; for (let j = 1; j < max; j++) { const next = table[i][j - 1] - Math.random() * table[i][j - 1] / 10; table[i].push(next.toFixed(4)); } } return table; } function getUniqueSize(table) { let set = new Set(); table.forEach(row => row.forEach(x => set.add(x))); return set.size; } function toPercent(x) { return (x * 100).toFixed(2).toString() + '%'; } async function runTestRerender() { const input = document.querySelector('input'); for (let i = 0; i < 10; i++) { await new Promise(resolve => { performance.mark('startRerender' + i); input.click(); setTimeout(() => { setTimeout(() => { performance.mark('endRerender' + i); performance.measure( 'measureRerender' + i, 'startRerender' + i, 'endRerender' + i ); resolve(); }, 0); }, 0); }); } } function willMount() { if (document.location.search.includes('test=true')) { performance.mark('startMount'); } } function didMount() { if (!document.location.search.includes('test=true')) { return; } performance.mark('endMount'); performance.measure('measureMount', 'startMount', 'endMount'); if (document.location.search.includes('butch=true')) { return runTestRerender(); } const input = document.querySelector('input'); performance.mark('startRerender'); input.click(); setTimeout(() => { performance.mark('endRerender'); performance.measure('measureRerender', 'startRerender', 'endRerender'); }, 0); } export default class App extends React.Component { constructor(props) { super(props); this.state = { table: getTable(), }; } componentWillMount() { willMount(); } componentDidMount() { didMount(); } handleClick = () => { this.setState({ table: getTable() }); }; render() { const { table: Table } = this.props; return ( <div> <div> <input type="submit" value="Generate" onClick={this.handleClick} /> {' '} <span>{getUniqueSize(this.state.table)} unique cells</span> </div> <Table table={this.state.table} toPercent={toPercent} /> </div> ); } }
src/App.js
one19/hourmon
import React, { Component } from 'react'; import { GOLD, BLACK } from './colors'; class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0 }; this.interval = setInterval(() => this.tick(), 2000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <h1 style={{ color: this.props.color }}> Counter ({this.props.increment}): {this.state.counter} </h1> ); } } export class App extends Component { render() { return ( <div> <Counter increment={1} color={GOLD} /> <Counter increment={2} color={BLACK} /> </div> ); } }
pages/nosotros.js
markhker/newCyK
import React, { Component } from 'react'; import './scss/about.scss'; import Paper from 'material-ui/lib/paper'; import CardTitle from 'material-ui/lib/card/card-title'; import CardText from 'material-ui/lib/card/card-text'; import Link from '../components/Link'; import MyRawTheme from '../components/theme'; import ThemeManager from 'material-ui/lib/styles/theme-manager'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; const style = { fontSize: 1.5+'rem', fontWeight: 200, }; @ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)) export default class extends Component { render() { return ( <div> <header className="about-header"> <div className="main-logo"> <a href="/"><img src="https://storage.googleapis.com/cykloud.appspot.com/static/img/tech/logo.png" alt="Logo C&K" /></a> </div> <h1>Nosotros</h1> </header> <section className="col-1 about-section-1"> <div className="col-1 col-s-20-24 col-m-22-24 col-l-20-24"> <h1 className="col-20-24">"We are your conection with the Cloud Technologies"</h1> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Quiénes" subtitle="Expertos" /> <CardText style={style}> Cloud & Kloud, somos un equipo de expertos en cloud computing. Nuestros compañeros trabajan por nuestro Qué y nuestro Por qué. Nos apasiona trabajar con gente emprendedora y organizaciones que produzcan trabajos excepcionales. </CardText> </Paper> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Qué" subtitle="Creamos" /> <CardText style={style}> Diseñamos las mejores soluciones de Cloud Computing a la medida de tu empresa. Ayudamos a tu organización a adaptarse a las nuevas tecnologías de la información, llegar más lejos y obtener todos los beneficios que la nube te ofrece. </CardText> </Paper> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Por qué" subtitle="Resultados" /> <CardText style={style}> Es simple. Nosotros existimos para enriquecer la calidad de vida de organizaciones y empresas. No se trata solo de hacer algo que se vea bien. Nos esforzamos y enfocamos en la acción, que genera resultados y se convierte en un cambio efectivo. </CardText> </Paper> </div> </section> <section className="col-1 standards"> <article className="col-1"> <div className="col-20-24 col-m-10-24 col-l-8-24 first"> <h2>Nuestras<br />Normas</h2> <div className="standard"> <h3>Personas sobre Ganancias</h3> <h4>No se trata de dinero</h4> <p>Nuestra norma de oro son las relaciones. Queremos trabajar con personas increíbles. Porque, para nosotros, el éxito se mide en experiencias positivas, no en la línea de fondo. Por eso, nos esforzamos en rodearnos de ambos inteligentes y apasionados miembros de equipo y clientes, esos que harán crecer nuestras mentes y corazones y no sólo nuestras carteras.</p> </div> <div className="standard"> <h3>KISS</h3> <h4>Por que es simple</h4> <p>Nuestras prácticas y soluciones son sencillas, porque sencillo = limpio = comprensible y ejecutable. Nosotros aplicamos este concepto a todos los aspectos del negocio, desde nuestro espacio de trabajo hasta los servicios que ofrecemos. También nos adherimos a la fuerza de la simplicidad cuando diseñamos y codificamos.</p> </div> <div className="standard"> <h3>Calidad sobre Cantidad</h3> <h4>Menos es más.</h4> <p>La energía mental tiene un ancho de banda agotable, por lo que concentramos nuestro tiempo y talento en un menor número de proyectos/clientes. Una mayor inversión de nuestra parte ,pero no estamos creando una pequeña fábrica de servicios de IT. Además priorizar la calidad sobre la cantidad apoya nuestros otros valores fundamentales.</p> </div> <div className="standard"> <h3>Haz más Preguntas</h3> <h4>Exige mejores respuestas</h4> <p>Creemos que empujar el sobre ayuda a consolidar y defender pensamientos/conceptos, y da nueva forma a la razón. Una idea o concepto fuerte resiste la prueba de estrés o será mejor en la línea de meta por haber sido objeto de escrutinio.</p> </div> </div> <div className="col-20-24 col-m-10-24 col-l-8-24 second"> <div className="standard"> <h3>Haz lo Mejor</h3> <h4>Siempre hay espacio para mejorar.</h4> <p>Este valor se mantiene constante en nuestras mentes, una intención definida en todos los puntos de contacto de nuestra organización. La llave que impulsa nuestra toma de decisiones y, en última instancia, nuestro producto final. Debido a que cada uno de nosotros acepta el reto de seguir subiendo la escalera de la grandeza.</p> </div> <div className="standard"> <h3>Mantenlo Real</h3> <h4>Las personas son personas</h4> <p>Y así es como los tratamos, independientemente de su rango o asociación. Todo el mundo merece respeto, transparencia y honestidad - los tres pilares de cada interacción que tenemos con colegas y clientes. Bono: el trabajo, y la vida en general, se vuelven más fáciles y productivas.</p> </div> <div className="standard"> <h3>Nunca Dejes de Aprender</h3> <h4>Rétate a ti mismo.</h4> <p>Cuando niños, éramos alimentados de educación a la fuerza, pero a medida que crecemos, nuestras interacciones académicas son menos frecuentes. A menos que las busques. Animamos a nuestro equipo a aprender: para perseguir sus pasiones, escucharnos unos a otros y acceder a nuevos conocimientos en conferencias, la biblioteca, los blogs y a través de otros medios. Ah, y para hacer más preguntas.</p> </div> <div className="standard"> <h3>Trabaja para Vivir</h3> <h4>La vida es primero.</h4> <p>El trabajo en sólo una pieza en el gráfico circular de la vida, y nuestro objetivo es que siga siendo así. Ya que somos tan fuertes como nuestro equipo, les animamos a trabajar duro, jugar duro y descansar duro. Siempre que podemos, les ayudamos a cultivar sus pasiones. Y tenemos en cuenta sus intereses y fortalezas cuando nos ponemos a trabajar. Después de todo, si amas lo que haces, en realidad nunca trabajas.</p> </div> </div> </article> </section> </div> ); } }
generators/app/templates/src/components/hello-world.js
trigun539/generator-ep-react-simple
import React, { Component } from 'react'; export default class HelloWorld extends Component { render () { return <h1>Hello World</h1>; } }
src/pages/Bookmarks/index.js
bogas04/SikhJS
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styled from 'react-emotion'; import { BOOKMARK_TYPES } from '../../constants'; import { clearAllBookmarks, getAllBookmarks, updateBookmarkTitle } from '../../bookmarks'; import { Textfield, Button, Toolbar, Loader } from '../../components'; import { Card, CardText, CardActions, CardTitle } from '../../components/Card'; const { SGGS, SHABAD } = BOOKMARK_TYPES; const SearchCardWrapper = styled.div` display: flex; flex-wrap: wrap; justify-content: center; flex-direction: column; width: 100%; align-items: center; `; const StyledLink = styled(Link)` text-decoration: none; color: teal; cursor: pointer; `; const SearchCard = ({ data: { title, key, value }, onTitleChange }) => ( <Card style={{ width: '30vw' }}> <CardTitle style={{ textTransform: 'capitalize' }}>{title}</CardTitle> <CardText> Edit Title <Textfield className="input" label={title} onChange={onTitleChange} type="text" defaultValue={title} /> </CardText> <CardActions> {key === SHABAD && <StyledLink to={`/shabads/${value}`}>Open Shabad</StyledLink>} {key === SGGS && <StyledLink to={`/SGGS/${value}`}>Open Ang {value}</StyledLink>} </CardActions> </Card> ); SearchCard.propTypes = { data: PropTypes.object, onTitleChange: PropTypes.func, }; const SearchCards = ({ items, onTitleChange }) => ( <SearchCardWrapper> { items .map(b => ( <SearchCard key={b.id} data={b} onTitleChange={({ currentTarget: { value: title = b.title } }) => onTitleChange({ ...b, title })} /> )) } </SearchCardWrapper> ); export default class Bookmarks extends Component { constructor (p) { super(p); this.state = { bookmarks: [], loading: true, keyword: '', }; getAllBookmarks() .then(bookmarks => this.setState({ bookmarks, loading: false })) .catch(err => console.error(err)); this.handleUpdateBookmark = this.handleUpdateBookmark.bind(this); this.handleClearAllBookmarks = this.handleClearAllBookmarks.bind(this); this.handleUpdateKeyword = this.handleUpdateKeyword.bind(this); } render () { let { loading, bookmarks, keyword } = this.state; if (keyword !== '') { bookmarks = bookmarks.filter(e => e.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1); } return ( <div> <Toolbar title={`Bookmarks`}> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <Textfield onChange={this.handleUpdateKeyword} placeholder="Search" /> <Button noBorder onClick={this.handleClearAllBookmarks}>Clear All Bookmarks</Button> </div> </Toolbar> <Loader loading={loading}>{ bookmarks.length === 0 ? <h1 style={{ textAlign: 'center' }}>No Bookmarks Found</h1> : <SearchCards items={bookmarks} onTitleChange={this.handleUpdateBookmark} /> } </Loader> </div> ); } handleUpdateBookmark ({ key, value, id, timestamp, title }) { updateBookmarkTitle({ key, value, id, timestamp, title }) .then(e => console.log(e)) .catch(err => console.error(err)); } handleClearAllBookmarks () { clearAllBookmarks() .then(() => this.setState({ bookmarks: [] })) .catch(err => console.error(err)); } handleUpdateKeyword ({ currentTarget: { value: keyword } }) { this.setState({ keyword }); } }
src/routes/Dashboard/View.js
cesine/rickshaw-react-sample
import React from 'react'; import PropTypes from 'prop-types'; import ChartByDayOfTheWeek from '../../components/ChartByDayOfTheWeek'; import ChartByHour from '../../components/ChartByHour'; import ChartDaysWithout from '../../components/ChartDaysWithout'; import ChartHistogram from '../../components/ChartHistogram'; import ChartPerDay from '../../components/ChartPerDay'; import ChartPerWeek from '../../components/ChartPerWeek'; import './Dashboard.css'; export default function Dashboard(props) { const { match: { params, }, history, deploysByHour, deploysPerDay, deploysPerWeek, deploysByDayOfTheWeek, deploysPerDayHistogram, } = props; function onDragZoom({ start, end }) { console.log('onDragZoom', start, end); history.push(`/start/${start.year}/${start.week}/${start.weekday}/end/${end.year}/${end.week}/${end.weekday}`); props.filterByStartAndEnd({ start, end }); } const style = { // eslint-disable-next-line no-undef height: window.innerHeight, }; const rows = 3; const columns = 2; return ( <div className="dashboard" style={style} > <div className="row"> <ChartByHour className="column" rowCount={rows} colCount={columns} title="Deploys by Hour" data={deploysByHour} params={params} /> <ChartPerDay className="column" rowCount={rows} colCount={columns} title="Deploys per Day" onDragZoom={onDragZoom} data={deploysPerDay} params={params} /> </div> <div className="row"> <ChartByDayOfTheWeek className="column" rowCount={rows} colCount={columns} title="Deploys by Day of the Week" data={deploysByDayOfTheWeek} params={params} /> <ChartPerWeek className="column" rowCount={rows} colCount={columns} title="Deploys per Week" onDragZoom={onDragZoom} data={deploysPerWeek} params={params} /> </div> <div className="row"> <ChartDaysWithout className="column" rowCount={rows} colCount={columns} title="Monday-Friday without Deploys" onDragZoom={onDragZoom} data={deploysPerDay} params={params} /> <ChartHistogram className="column" rowCount={rows} colCount={columns} title="Monday-Friday deploy frequency" data={deploysPerDayHistogram} params={params} /> </div> </div>); } Dashboard.propTypes = { history: PropTypes.shape({}).isRequired, match: PropTypes.shape({ parmams: PropTypes.shape({}), }).isRequired, filterByStartAndEnd: PropTypes.func.isRequired, deploysByHour: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerDay: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysByDayOfTheWeek: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerWeek: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerDayHistogram: PropTypes.arrayOf(PropTypes.shape({})).isRequired, };
src/front-end/js/pages/Registration.js
aleksey-gonchar/emmofret
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import _ from 'lodash' import * as AppActions from '../actions/AppActions.js' import FullNameInput from '../components/inputs/FullNameInput.js' import EmailInput from '../components/inputs/EmailInput.js' import PasswordInput from '../components/inputs/PasswordInput.js' import { Modal, Button } from 'react-bootstrap' const { Header, Body, Title, Footer, Dialog } = Modal function actions (dispatch) { return { actions: { signUp: bindActionCreators(AppActions.signUp, dispatch) } } } @connect(null, actions) export default class SignUpModal extends React.Component { static propTypes = { actions: React.PropTypes.object } constructor (props) { super(props) this.state = { form: { fullName: '', email: '', password: '' }, isFormCompleted: false } this.signUp = this.signUp.bind(this) this.checkSubmitBtnState = _.debounce(this.checkSubmitBtnState, 200) this.onChangeFormState = this.onChangeFormState.bind(this) this.submitOnReturn = this.submitOnReturn.bind(this) } checkSubmitBtnState () { let isAllValid = _.every(this.state.form, (prop, key) => { if (_.isObject(prop)) { return prop.isValid } else { return false } }) this.setState({ isFormCompleted: isAllValid }) } onChangeFormState (propName) { return (newValue) => { let state = { form: this.state.form } state.form[propName] = newValue this.setState(state) this.checkSubmitBtnState() } } signUp () { const payload = { user: { firstName: this.state.form.fullName.firstName, lastName: this.state.form.fullName.lastName, email: this.state.form.email.value, password: this.state.form.password.value }, shake: { selector: '[data-class="Registration"]', style: 'horizontal' } } this.props.actions.signUp(payload) } submitOnReturn (e) { if (e.charCode === 13 && this.state.isFormCompleted) { this.signUp() } } render () { let btnProps = {} if (this.state.isFormCompleted) { btnProps.disabled = false } else { btnProps.disabled = true } let inputProps = { onKeyPress: this.submitOnReturn } return ( <div className='modal-static'> <Dialog onHide={ () => {} } bsSize='sm' data-class='Registration'> <Header> <Title>Sign up</Title> </Header> <Body> <FullNameInput onSave={this.onChangeFormState('fullName')} {...inputProps}/> <EmailInput onSave={this.onChangeFormState('email')} {...inputProps}/> <PasswordInput onSave={this.onChangeFormState('password')} {...inputProps}/> </Body> <Footer> <Button bsStyle='primary' onClick={this.signUp} {...btnProps}>Sign up</Button> </Footer> </Dialog> </div> ) } }
src/assets/js/react/components/FontManager/FontVariantLabel.js
GravityPDF/gravity-forms-pdf-extended
/* Dependencies */ import React from 'react' import PropTypes from 'prop-types' import { sprintf } from 'sprintf-js' /** * @package Gravity PDF * @copyright Copyright (c) 2021, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 6.0 */ /** * Display information for drop box font variant label * * @param label * @param font * * @since 6.0 */ const FontVariantLabel = ({ label, font }) => ( <div data-test='component-FontVariantLabel' htmlFor={'gfpdf-font-variant-' + label}> {(label === 'regular' && font === 'false') && ( <span dangerouslySetInnerHTML={{ __html: sprintf(GFPDF.fontListRegularRequired, '' + "<span class='required'>", '</span>') }} /> )} {(label === 'regular' && font === 'true') && GFPDF.fontListRegular} {label === 'italics' && GFPDF.fontListItalics} {label === 'bold' && GFPDF.fontListBold} {label === 'bolditalics' && GFPDF.fontListBoldItalics} </div> ) /** * PropTypes * * @since 6.0 */ FontVariantLabel.propTypes = { label: PropTypes.string.isRequired, font: PropTypes.string } export default FontVariantLabel
src/svg-icons/maps/local-play.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPlay = (props) => ( <SvgIcon {...props}> <path d="M20 12c0-1.1.9-2 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2zm-4.42 4.8L12 14.5l-3.58 2.3 1.08-4.12-3.29-2.69 4.24-.25L12 5.8l1.54 3.95 4.24.25-3.29 2.69 1.09 4.11z"/> </SvgIcon> ); MapsLocalPlay = pure(MapsLocalPlay); MapsLocalPlay.displayName = 'MapsLocalPlay'; MapsLocalPlay.muiName = 'SvgIcon'; export default MapsLocalPlay;
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/directions-bus.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsDirectionsBus = (props) => ( <SvgIcon {...props}> <path d="M4 16c0 .88.39 1.67 1 2.22V20c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h8v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1.78c.61-.55 1-1.34 1-2.22V6c0-3.5-3.58-4-8-4s-8 .5-8 4v10zm3.5 1c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm9 0c-.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.5zm1.5-6H6V6h12v5z"/> </SvgIcon> ); MapsDirectionsBus.displayName = 'MapsDirectionsBus'; MapsDirectionsBus.muiName = 'SvgIcon'; export default MapsDirectionsBus;
kit/entry/browser.js
Mahi22/MedTantra
// Browser entry point, for Webpack. We'll grab the browser-flavoured // versions of React mounting, routing etc to hook into the DOM // ---------------------- // IMPORTS /* NPM */ // Enable async/await and generators, cross-browser import 'regenerator-runtime/runtime'; // Patch global.`fetch` so that Apollo calls to GraphQL work import 'isomorphic-fetch'; // React parts import React from 'react'; import ReactDOM from 'react-dom'; // Browser routing import { BrowserRouter } from 'react-router-dom'; // Apollo Provider. This HOC will 'wrap' our React component chain // and handle injecting data down to any listening component import { ApolloProvider } from 'react-apollo'; /* MedTantra */ // Root component. This is our 'entrypoint' into the app. If you're using // the MedTantra starter kit for the first time, `src/app.js` is where // you can start editing to add your own code. Note: This first is imported // first, since it sets up our app's settings import App from 'src/app'; // Grab the shared Apollo Client import { browserClient } from 'kit/lib/apollo'; // Custom redux store creator. This will allow us to create a store 'outside' // of Apollo, so we can apply our own reducers and make use of the Redux dev // tools in the browser import createNewStore from 'kit/lib/redux'; // ---------------------- // Create a new browser Apollo client const client = browserClient(); // Create a new Redux store const store = createNewStore(client); // Create the 'root' entry point into the app. If we have React hot loading // (i.e. if we're in development), then we'll wrap the whole thing in an // <AppContainer>. Otherwise, we'll jump straight to the browser router function doRender() { ReactDOM.hydrate( <Root />, document.getElementById('main'), ); } // The <Root> component. We'll run this as a self-contained function since // we're using a bunch of temporary vars that we can safely discard. // // If we have hot reloading enabled (i.e. if we're in development), then // we'll wrap the whole thing in <AppContainer> so that our views can respond // to code changes as needed const Root = (() => { // Wrap the component hierarchy in <BrowserRouter>, so that our children // can respond to route changes const Chain = () => ( <ApolloProvider store={store} client={client}> <BrowserRouter> <App /> </BrowserRouter> </ApolloProvider> ); // React hot reloading -- only enabled in development. This branch will // be shook from production, so we can run a `require` statement here // without fear that it'll inflate the bundle size if (module.hot) { // <AppContainer> will respond to our Hot Module Reload (HMR) changes // back from WebPack, and handle re-rendering the chain as needed const AppContainer = require('react-hot-loader').AppContainer; // Start our 'listener' at the root component, so that any changes that // occur in the hierarchy can be captured module.hot.accept('src/app', () => { // Refresh the entry point of our app, to get the changes. // eslint-disable-next-line require('src/app').default; // Re-render the hierarchy doRender(); }); return () => ( <AppContainer> <Chain /> </AppContainer> ); } return Chain; })(); doRender();
app/src/scripts/widgets/UserProfile/UserProfile.js
vyorkin/assignment
import React from 'react'; export default class UserProfile { render() { return ( <dl> <dt>Фамилия:</dt><dd>{this.props.lastName}</dd> <dt>Имя:</dt><dd>{this.props.firstName}</dd> <dt>Отчество:</dt><dd>{this.props.middleName}</dd> </dl> ); } }
src/Affix.js
pandoraui/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import AffixMixin from './AffixMixin'; const Affix = React.createClass({ mixins: [AffixMixin], render() { let holderStyle = { top: this.state.affixPositionTop, // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; return ( <div {...this.props} className={classNames(this.props.className, this.state.affixClass)} style={holderStyle}> {this.props.children} </div> ); } }); export default Affix;
test/test_helper.js
rickywid/micdb
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/svg-icons/av/web.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvWeb = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/> </SvgIcon> ); AvWeb = pure(AvWeb); AvWeb.displayName = 'AvWeb'; AvWeb.muiName = 'SvgIcon'; export default AvWeb;
React-Youtube/src/components/videoDetail.js
vivekbharatha/ModernReactWithReduxCourseUdemy
import React from 'react'; const VideoDetail = ({ video }) => { if (!video) { return <div>Started the Engine, hold you sugar !</div> } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9 video-player"> <iframe src={ url } className="embed-responsive-item"> </iframe> </div> <div className="video-details"> <div>{ video.snippet.title }</div> <div>{ video.snippet.description }</div> </div> </div> ); } export default VideoDetail;
src/components/gameTimerComponent/gameTimerComponent.js
craigbilner/quizapp
'use strict'; import React from 'react'; import radium from 'radium'; class GameTimerComponent extends React.Component { constructor(props) { super(props); } timeFunc() { this.props.onTimeChange(this.props.gameTime - (this.props.timeInterval / 1000)); if (this.props.gameTime !== 0) { this.startTimer(); } } startTimer() { if (!this.props.isPaused) { this.timer = setTimeout(this.timeFunc.bind(this), this.props.timeInterval); } } clearTimer() { clearTimeout(this.timer); this.timer = 0; } componentDidMount() { this.startTimer(); } componentWillUnmount() { this.clearTimer(); } render() { if (this.props.isReset) { this.clearTimer(); this.startTimer(); } const compStyle = [ { color: this.props.baseStyles.colours.dark.primary } ]; return ( <span style={compStyle}>{this.props.gameTime}</span> ); } } GameTimerComponent.propTypes = { gameTime: React.PropTypes.number.isRequired, isPaused: React.PropTypes.bool.isRequired, isReset: React.PropTypes.bool.isRequired, onTimeChange: React.PropTypes.func, timeInterval: React.PropTypes.number.isRequired, baseStyles: React.PropTypes.object.isRequired }; GameTimerComponent.defaultProps = {}; export default radium(GameTimerComponent);
examples/dynamic-segments/app.js
upraised/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ObjectDestructuring.js
GreenGremlin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-object-destructuring"> {this.state.users.map(user => { const { id, ...rest } = user; // eslint-disable-next-line no-unused-vars const [{ name, ...innerRest }] = [{ ...rest }]; return <div key={id}>{name}</div>; })} </div> ); } }
src/components/Image/Image.js
dialogs/dialog-web-components
/* * Copyright 2019 dialog LLC <[email protected]> * @flow */ import React from 'react'; import classNames from 'classnames'; import getImageSize from '../../utils/getImageSize'; import ImagePreloader, { type ImagePreloaderState, STATE_SUCCESS, } from '../ImagePreloader/ImagePreloader'; import styles from './Image.css'; export type ImageProps = { className?: string, src: ?string, id?: string, alt?: ?string, preview?: ?string, width: number, height: number, maxWidth: number, maxHeight: number, onClick?: (event: SyntheticMouseEvent<>) => mixed, }; function Image(props: ImageProps) { return ( <ImagePreloader src={props.src}> {({ state, src }: ImagePreloaderState) => { const { width, height } = getImageSize( props.width, props.height, props.maxWidth, props.maxHeight, ); const className = classNames( styles.container, { [styles.loaded]: state === STATE_SUCCESS, }, props.className, ); const source = state === STATE_SUCCESS ? src : props.preview; return ( <div className={className} title={props.alt} style={{ width, height }} > {source ? ( <img id={props.id} src={source} width={width} height={height} alt={props.alt} onClick={props.onClick} className={styles.image} /> ) : null} </div> ); }} </ImagePreloader> ); } Image.defaultProps = { maxWidth: 400, maxHeight: 400, }; export default Image;
src/svg-icons/device/settings-system-daydream.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSettingsSystemDaydream = (props) => ( <SvgIcon {...props}> <path d="M9 16h6.5c1.38 0 2.5-1.12 2.5-2.5S16.88 11 15.5 11h-.05c-.24-1.69-1.69-3-3.45-3-1.4 0-2.6.83-3.16 2.02h-.16C7.17 10.18 6 11.45 6 13c0 1.66 1.34 3 3 3zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/> </SvgIcon> ); DeviceSettingsSystemDaydream = pure(DeviceSettingsSystemDaydream); DeviceSettingsSystemDaydream.displayName = 'DeviceSettingsSystemDaydream'; DeviceSettingsSystemDaydream.muiName = 'SvgIcon'; export default DeviceSettingsSystemDaydream;
src/containers/Home/Home.js
trueter/react-redux-universal-hot-example
import React, { Component } from 'react'; import { Link } from 'react-router'; import { CounterButton, GithubButton } from 'components'; import config from '../../config'; import Helmet from 'react-helmet'; export default class Home extends Component { render() { const styles = require('./Home.scss'); // require the logo image both from client and server const logoImage = require('./logo.png'); return ( <div className={styles.home}> <Helmet title="Home"/> <div className={styles.masthead}> <div className="container"> <div className={styles.logo}> <p> <img src={logoImage}/> </p> </div> <h1>{config.app.title}</h1> <h2>{config.app.description}</h2> <p> <a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example" target="_blank"> <i className="fa fa-github"/> View on Github </a> </p> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="star" width={160} height={30} count large/> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="fork" width={160} height={30} count large/> <p className={styles.humility}> Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>. </p> </div> </div> <div className="container"> <div className={styles.counterContainer}> <CounterButton multireducerKey="counter1"/> <CounterButton multireducerKey="counter2"/> <CounterButton multireducerKey="counter3"/> </div> <p>This starter boilerplate app uses the following technologies:</p> <ul> <li> <del>Isomorphic</del> {' '} <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering </li> <li>Both client and server make calls to load data from separate API server</li> <li><a href="https://github.com/facebook/react" target="_blank">React</a></li> <li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li> <li><a href="http://expressjs.com" target="_blank">Express</a></li> <li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li> <li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li> <li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a> </li> <li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li> <li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation </li> <li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next generation DX (developer experience). Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>. </li> <li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep your router state in your Redux store </li> <li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li> <li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state in Redux </li> <li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several identical reducer states into one key-based reducer</li> <li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of stylesheets </li> <li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome </li> <li><a href="http://socket.io/">socket.io</a> for real-time communication</li> </ul> <h3>Features demonstrated in this project</h3> <dl> <dt>Multiple components subscribing to same redux store slice</dt> <dd> The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component that fetches data from the server initially, but allows for the user to refresh the data from the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same data. </dd> <dt>Server-side data loading</dt> <dd> The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s <code>asyncConnect()</code> function is called before the widgets page is loaded, on either the server or the client, allowing all the widget data to be loaded and ready for the page to render. </dd> <dt>Data loading errors</dt> <dd> The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of the time to highlight this. The <code>clientMiddleware</code> sends an error action which the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user. </dd> <dt>Session based login</dt> <dd> On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server and stored in the session. Subsequent refreshes will show that you are still logged in. </dd> <dt>Redirect after state change</dt> <dd> After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>, and pulls the router from the context. </dd> <dt>Auth-required views</dt> <dd> The aforementioned Login Success page is only visible to you if you are logged in. If you try to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back to this home page. This <strike>magic</strike> logic is performed by the <code>onEnter</code> hook within <code>routes.js</code>. </dd> <dt>Forms</dt> <dd> The <Link to="/survey">Survey page</Link> uses the still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state inside the Redux store. This includes immediate client-side validation. </dd> <dt>WebSockets / socket.io</dt> <dd> The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time communication between clients. You need to <Link to="/login">login</Link> first. </dd> </dl> <h3>From the author</h3> <p> I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015, all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as quickly as they have come into it, but I personally believe that this stack is the future of web development and will survive for several years. I'm building my new projects like this, and I recommend that you do, too. </p> <p>Thanks for taking the time to check this out.</p> <p>– Erik Rasmussen</p> </div> </div> ); } }
app/routes.js
ndnhat/te-starter
'use strict'; import React from 'react'; import Router from 'react-router'; let { Route, DefaultRoute, NotFoundRoute } = Router; // -- Import base components import Layout from './components/layout'; import Login from './components/auth/login'; export default ( <Route handler={Layout} path='/'> <Route name='login' handler={Login} /> </Route> );
app/javascript/flavours/glitch/features/getting_started_misc/index.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Column from 'flavours/glitch/features/ui/components/column'; import ColumnBackButtonSlim from 'flavours/glitch/components/column_back_button_slim'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from 'flavours/glitch/features/ui/components/column_link'; import ColumnSubheading from 'flavours/glitch/features/ui/components/column_subheading'; import { openModal } from 'flavours/glitch/actions/modal'; import { connect } from 'react-redux'; const messages = defineMessages({ heading: { id: 'column.heading', defaultMessage: 'Misc' }, subheading: { id: 'column.subheading', defaultMessage: 'Miscellaneous options' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' }, show_me_around: { id: 'getting_started.onboarding', defaultMessage: 'Show me around' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned posts' }, info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' }, keyboard_shortcuts: { id: 'navigation_bar.keyboard_shortcuts', defaultMessage: 'Keyboard shortcuts' }, featured_users: { id: 'navigation_bar.featured_users', defaultMessage: 'Featured users' }, }); export default @connect() @injectIntl class gettingStartedMisc extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; openOnboardingModal = (e) => { this.props.dispatch(openModal('ONBOARDING')); } openFeaturedAccountsModal = (e) => { this.props.dispatch(openModal('PINNED_ACCOUNTS_EDITOR')); } render () { const { intl } = this.props; let i = 1; return ( <Column icon='ellipsis-h' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <div className='scrollable'> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> <ColumnLink key='{i++}' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' /> <ColumnLink key='{i++}' icon='thumb-tack' text={intl.formatMessage(messages.pins)} to='/pinned' /> <ColumnLink key='{i++}' icon='users' text={intl.formatMessage(messages.featured_users)} onClick={this.openFeaturedAccountsModal} /> <ColumnLink key='{i++}' icon='volume-off' text={intl.formatMessage(messages.mutes)} to='/mutes' /> <ColumnLink key='{i++}' icon='ban' text={intl.formatMessage(messages.blocks)} to='/blocks' /> <ColumnLink key='{i++}' icon='minus-circle' text={intl.formatMessage(messages.domain_blocks)} to='/domain_blocks' /> <ColumnLink key='{i++}' icon='question' text={intl.formatMessage(messages.keyboard_shortcuts)} to='/keyboard-shortcuts' /> <ColumnLink key='{i++}' icon='book' text={intl.formatMessage(messages.info)} href='/about/more' /> <ColumnLink key='{i++}' icon='hand-o-right' text={intl.formatMessage(messages.show_me_around)} onClick={this.openOnboardingModal} /> </div> </Column> ); } }
lib/index.js
thatPamIAm/weathrly
import React from 'react'; import ReactDOM from 'react-dom'; import App from './containers/App'; import reset from '../css/reset'; import styles from '../css/styles'; ReactDOM.render(<App />, document.getElementById('application'));
docs/app/Examples/modules/Progress/Content/ProgressExampleProgress.js
vageeshb/Semantic-UI-React
import React from 'react' import { Progress } from 'semantic-ui-react' const ProgressExampleProgress = () => ( <Progress percent={44} progress /> ) export default ProgressExampleProgress
examples/real-world/containers/Root.js
Lucifier129/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
Realization/frontend/czechidm-acc/src/content/system/SystemRoles.js
bcvsolutions/CzechIdMng
import React from 'react'; import _ from 'lodash'; // import { Basic, Domain } from 'czechidm-core'; import RoleSystemTableComponent, { RoleSystemTable } from '../role/RoleSystemTable'; const uiKey = 'system-roles-table'; /** * Table to display roles, assigned to system * * @author Petr Hanák * @author Radek Tomiška */ export default class SystemRoles extends Basic.AbstractContent { getUiKey() { return uiKey; } getContentKey() { return 'acc:content.system.roles'; } getNavigationKey() { return 'system-roles'; } render() { const { entityId } = this.props.match.params; const forceSearchParameters = new Domain.SearchParameters().setFilter('systemId', entityId); // return ( <div className="tab-pane-table-body"> { this.renderContentHeader({ style: { marginBottom: 0 }}) } <Basic.Panel className="no-border last"> <RoleSystemTableComponent columns={ _.difference(RoleSystemTable.defaultProps.columns, ['system']) } showRowSelection uiKey={ `${this.getUiKey()}-${entityId}` } forceSearchParameters={ forceSearchParameters } menu="system" match={ this.props.match } className="no-margin"/> </Basic.Panel> </div> ); } }
react-flux-mui/js/material-ui/src/svg-icons/device/battery-90.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery90 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/> </SvgIcon> ); DeviceBattery90 = pure(DeviceBattery90); DeviceBattery90.displayName = 'DeviceBattery90'; DeviceBattery90.muiName = 'SvgIcon'; export default DeviceBattery90;
app/javascript/mastodon/features/compose/containers/warning_container.js
kibousoft/mastodon
import React from 'react'; import { connect } from 'react-redux'; import Warning from '../components/warning'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { me } from '../../../initial_state'; const APPROX_HASHTAG_RE = /(?:^|[^\/\)\w])#(\S+)/i; const mapStateToProps = state => ({ needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']), hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])), }); const WarningWrapper = ({ needsLockWarning, hashtagWarning }) => { if (needsLockWarning) { return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />; } if (hashtagWarning) { return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />; } return null; }; WarningWrapper.propTypes = { needsLockWarning: PropTypes.bool, hashtagWarning: PropTypes.bool, }; export default connect(mapStateToProps)(WarningWrapper);
app/components/Home.js
rondobley/meal-planner
import React from 'react'; import ReactDOM from 'react-dom'; import HomeStore from '../stores/HomeStore'; import HomeActions from '../actions/HomeActions'; class Home extends React.Component { constructor(props) { super(props); this.state = HomeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HomeStore.listen(this.onChange); } componentWillUnmount() { HomeStore.unlisten(this.onChange); } componentDidUpdate() { if(this.state.isLoggedIn) { window.location.href = "/dishes"; } } onChange(state) { this.setState(state); } resetValidationState() { this.state.emailHelpBlock = ''; this.state.passwordHelpBlock = ''; this.state.formHelpBlock = ''; this.state.formValidationState = ''; } handleSubmit(e) { e.preventDefault(); this.resetValidationState(); var email = this.state.email.trim(); var password = this.state.password.trim(); if(!email) { HomeActions.invalidEmail(); ReactDOM.findDOMNode(this.refs.emailInput).focus(); } else if(!password) { HomeActions.invalidPassword(); ReactDOM.findDOMNode(this.refs.passwordInput).focus(); } else { HomeActions.login(email, password); } } render() { let button = <button type='submit' className='btn btn-primary'>Login</button>; return ( <div className='container'> <div className='row'> <div className='col-md-3'></div> <div className='col-sm-12 col-md-6'> <form className='login-form' onSubmit={this.handleSubmit.bind(this)}> <div className={'form-group ' + this.state.formValidationState}> <label className='control-label'>Login</label> <input type='text' className='form-control' ref='emailInput' name="email" value={this.state.email} onChange={HomeActions.updateEmailInput} autoFocus/> <span className='help-block'>{this.state.emailHelpBlock}</span> <input type='password' className='form-control' ref='passwordInput' name="password" value={this.state.password} onChange={HomeActions.updatePasswordInput} /> <span className='help-block'>{this.state.passwordHelpBlock}</span> <span className='help-block'>{this.state.formHelpBlock}</span> </div> <div className="text-right">{button}</div> </form> </div> <div className='col-md-3'></div> </div> </div> ); } } export default Home;
src/svg-icons/social/people-outline.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPeopleOutline = (props) => ( <SvgIcon {...props}> <path d="M16.5 13c-1.2 0-3.07.34-4.5 1-1.43-.67-3.3-1-4.5-1C5.33 13 1 14.08 1 16.25V19h22v-2.75c0-2.17-4.33-3.25-6.5-3.25zm-4 4.5h-10v-1.25c0-.54 2.56-1.75 5-1.75s5 1.21 5 1.75v1.25zm9 0H14v-1.25c0-.46-.2-.86-.52-1.22.88-.3 1.96-.53 3.02-.53 2.44 0 5 1.21 5 1.75v1.25zM7.5 12c1.93 0 3.5-1.57 3.5-3.5S9.43 5 7.5 5 4 6.57 4 8.5 5.57 12 7.5 12zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 5.5c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z"/> </SvgIcon> ); SocialPeopleOutline = pure(SocialPeopleOutline); SocialPeopleOutline.displayName = 'SocialPeopleOutline'; SocialPeopleOutline.muiName = 'SvgIcon'; export default SocialPeopleOutline;
docs/src/app/components/pages/components/SvgIcon/Page.js
igorbt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconReadmeText from './README'; import IconExampleSimple from './ExampleSimple'; import iconExampleSimpleCode from '!raw!./ExampleSimple'; import IconExampleIcons from './ExampleIcons'; import iconExampleIconsCode from '!raw!./ExampleIcons'; import iconCode from '!raw!material-ui/SvgIcon/SvgIcon'; const descriptions = { custom: 'This example uses a custom svg icon. The third example has a `hoverColor` defined.', material: 'This examples demonstrates how to use the included _Material icon_ components.', }; const SvgIconPage = () => ( <div> <Title render={(previousTitle) => `Svg Icon - ${previousTitle}`} /> <MarkdownElement text={iconReadmeText} /> <CodeExample title="Custom SVG icon" description={descriptions.custom} code={iconExampleSimpleCode} > <IconExampleSimple /> </CodeExample> <CodeExample title="Material icons" description={descriptions.material} code={iconExampleIconsCode} > <IconExampleIcons /> </CodeExample> <PropTypeDescription code={iconCode} /> </div> ); export default SvgIconPage;
src/components/RadioButton/RadioButton-story.js
wfp/ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, boolean, text } from '@storybook/addon-knobs'; import RadioButton from '../RadioButton'; import RadioButtonSkeleton from '../RadioButton/RadioButton.Skeleton'; const radioProps = () => ({ className: 'some-class', name: text('Form item name (name)', 'test'), value: text('Value (value)', 'standard'), labelText: text('Label text (labelText)', 'Standard Radio Button'), checked: boolean('Checked (checked)', false), disabled: boolean('Disabled (disabled)', false), onChange: action('onChange'), }); storiesOf('Components|RadioButton', module) .addDecorator(withKnobs) .add('Default', () => <RadioButton id="radio-1" {...radioProps()} />) .add('skeleton', () => ( <div> <RadioButtonSkeleton /> </div> ));
packages/wix-style-react/src/ListItemSection/docs/index.story.js
wix/wix-style-react
import React from 'react'; import Star from 'wix-ui-icons-common/Star'; import Download from 'wix-ui-icons-common/Download'; import Hint from 'wix-ui-icons-common/Hint'; import { header, tabs, tab, description, importExample, title, columns, divider, example as baseExample, playground, api, testkit, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import ListItemSection from '..'; import Box from '../../Box'; const example = config => baseExample({ components: { Star, Download, Hint }, ...config, }); export default { category: storySettings.category, storyName: 'ListItemSection', component: ListItemSection, componentPath: '..', componentProps: { title: 'List item Section title', suffix: 'Suffix', type: 'title', ellipsis: false, }, sections: [ header({ component: ( <Box width="500px" backgroundColor="#f0f4f7" padding="25px" border="1px solid #e5e5e5" > <ListItemSection title="List Item Section" suffix="Suffix" /> </Box> ), }), tabs([ tab({ title: 'Description', sections: [ columns([ description({ title: 'Description', text: 'ListItemSection is an internal component which is used to build dropdown or menu like components. Usually this item should not be used by consumers, though custom options builder is exposed for usage with DropdownBase.', }), ]), importExample(` // Use directly import { ListItemSection } from 'wix-style-react'; // Or use a builder import { listItemSectionBuilder } from 'wix-style-react'; `), divider(), title('Examples'), example({ title: 'Types', text: 'Component divides lists by 4 types – adding title, subheader, divider or simnple whitespace.', source: ` <Layout cols={1}> <ListItemSection title="Section title" /> <ListItemSection type="subheader" title="Subheader title" /> <ListItemSection type="divider" /> <ListItemSection type="whitespace" /> </Layout> `, }), example({ title: 'Suffix', text: 'For actions title and subheader types support a suffix.', source: ` <Layout cols={1}> <ListItemSection title="Title area" suffix="Suffix Action" /> <ListItemSection title="Title area" suffix={<InfoIcon content="Tooltip content!" />} /> <ListItemSection type="subheader" title="Title area" suffix="Suffix Action" /> <ListItemSection type="subheader" title="Title area" suffix={<InfoIcon content="Tooltip content!" />} /> </Layout> `, }), example({ title: 'Text cropping', text: 'By default component wraps the text. If needed it can be configured to show ellipsis and display full value on hover.', source: ` <Layout cols={1}> <Cell> <ListItemSection ellipsis title="This is a very very very very long text that will be cropped by ellipsis at some point" suffix="Nice long long long long long Suffix" /> </Cell> <Cell> <ListItemSection title="This is a very very very very long text that will *not* be cropped by ellipsis at some point" suffix="Nice long long long long long Suffix" /> </Cell> </Layout> `, }), example({ title: 'Advanced Example 1', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemSectionBuilder({ title: 'Most Popular', }), listItemSelectBuilder({ id: 0, title: 'Wix Stores', }), listItemSelectBuilder({ id: 1, title: 'Wix Bookings', }), listItemSelectBuilder({ id: 2, title: 'Wix Blog', }), listItemSectionBuilder({ title: 'Other', }), listItemSelectBuilder({ title: 'Wix Events', }), listItemSelectBuilder({ id: 3, title: 'Wix Forum', }), listItemSelectBuilder({ id: 4, title: 'Wix Restaurants', }), listItemActionBuilder({ id: 5, title: 'See All Results', }), ]} /> </Box> `, }), example({ title: 'Advanced Example 2', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemActionBuilder({ id: 0, skin: 'dark', size: 'small', title: 'Edit', prefixIcon: <Icons.EditSmall />, }), listItemActionBuilder({ id: 1, skin: 'dark', size: 'small', title: 'Duplicate', prefixIcon: <Icons.EditSmall />, }), listItemActionBuilder({ id: 3, skin: 'dark', size: 'small', title: 'Move to', prefixIcon: <Icons.MoveToSmall />, }), listItemSectionBuilder({ type: 'divider', }), listItemActionBuilder({ id: 4, skin: 'dark', size: 'small', title: 'Archive', prefixIcon: <Icons.ArchiveSmall />, }), listItemActionBuilder({ id: 4, skin: 'destructive', size: 'small', title: 'Delete', prefixIcon: <Icons.DeleteSmall />, }), ]} /> </Box> `, }), example({ title: 'Advanced Example 3', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemSectionBuilder({ title: 'Admins', type: 'subheader', suffix: 'Edit', }), listItemSelectBuilder({ id: 0, title: 'John Wilson', }), listItemSelectBuilder({ id: 1, title: 'Silvester Grant', }), listItemSectionBuilder({ title: 'Members', type: 'subheader', suffix: 'Edit', }), listItemSelectBuilder({ title: 'Jason Angel', }), listItemSelectBuilder({ id: 3, title: 'Kalvin Mcleod', }), listItemSelectBuilder({ id: 4, title: 'Ro Giberton', }), ]} /> </Box> `, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };
src/svg-icons/notification/airline-seat-recline-normal.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineNormal = (props) => ( <SvgIcon {...props}> <path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/> </SvgIcon> ); NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal); NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal'; NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineNormal;
src/icons/IosGameControllerB.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosGameControllerB extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M135.123,204.568c-10.688,0-19.343,8.717-19.343,19.441c0,10.727,8.655,19.447,19.343,19.447 c10.641,0,19.297-8.721,19.297-19.447C154.42,213.285,145.764,204.568,135.123,204.568z"></path> <path d="M466.279,248.866c-21.157-88.471-43.631-135.489-88.454-148.83C368.06,97.135,359.748,96,352.076,96 c-27.598,0-46.938,14.683-96.08,14.683c-49.174,0-68.502-14.681-96.062-14.683c-7.665,0-15.963,1.135-25.721,4.036 c-44.869,13.341-67.342,60.359-88.461,148.83c-21.181,88.473-17.334,152.363,7.679,164.289C57.502,415.1,61.662,416,65.885,416 c21.694,0,45.139-23.838,67.659-52.047C159.198,331.848,165.658,331,243.822,331h24.343c78.147,0,84.628,0.846,110.282,32.953 c22.526,28.207,45.97,52.004,67.665,52.004c4.226,0,8.384-0.879,12.457-2.823C483.574,401.208,487.421,337.339,466.279,248.866z M135.234,263.633C113.594,263.633,96,245.875,96,224.01c0-21.84,17.594-39.643,39.234-39.643 c21.655,0,39.249,17.803,39.249,39.643C174.483,245.875,156.89,263.633,135.234,263.633z M308.076,244.14 c-11.058,0-20.076-9.019-20.076-20.107c0-11.09,9.019-20.104,20.076-20.104c11.131,0,20.148,9.014,20.148,20.104 C328.225,235.121,319.207,244.14,308.076,244.14z M351.988,288c-11.058,0-20.053-8.951-20.053-20.016 c0-11.157,8.995-20.106,20.053-20.106c11.146,0,20.148,8.949,20.148,20.106C372.137,279.049,363.134,288,351.988,288z M351.988,200.19c-11.058,0-20.053-8.993-20.053-20.083c0-11.094,8.995-20.107,20.053-20.107c11.146,0,20.148,9.014,20.148,20.107 C372.137,191.197,363.134,200.19,351.988,200.19z M395.947,244.14c-11.105,0-20.101-9.019-20.101-20.107 c0-11.09,8.995-20.104,20.101-20.104c11.059,0,20.053,9.014,20.053,20.104C416,235.121,407.006,244.14,395.947,244.14z"></path> </g> </g>; } return <IconBase> <g> <path d="M135.123,204.568c-10.688,0-19.343,8.717-19.343,19.441c0,10.727,8.655,19.447,19.343,19.447 c10.641,0,19.297-8.721,19.297-19.447C154.42,213.285,145.764,204.568,135.123,204.568z"></path> <path d="M466.279,248.866c-21.157-88.471-43.631-135.489-88.454-148.83C368.06,97.135,359.748,96,352.076,96 c-27.598,0-46.938,14.683-96.08,14.683c-49.174,0-68.502-14.681-96.062-14.683c-7.665,0-15.963,1.135-25.721,4.036 c-44.869,13.341-67.342,60.359-88.461,148.83c-21.181,88.473-17.334,152.363,7.679,164.289C57.502,415.1,61.662,416,65.885,416 c21.694,0,45.139-23.838,67.659-52.047C159.198,331.848,165.658,331,243.822,331h24.343c78.147,0,84.628,0.846,110.282,32.953 c22.526,28.207,45.97,52.004,67.665,52.004c4.226,0,8.384-0.879,12.457-2.823C483.574,401.208,487.421,337.339,466.279,248.866z M135.234,263.633C113.594,263.633,96,245.875,96,224.01c0-21.84,17.594-39.643,39.234-39.643 c21.655,0,39.249,17.803,39.249,39.643C174.483,245.875,156.89,263.633,135.234,263.633z M308.076,244.14 c-11.058,0-20.076-9.019-20.076-20.107c0-11.09,9.019-20.104,20.076-20.104c11.131,0,20.148,9.014,20.148,20.104 C328.225,235.121,319.207,244.14,308.076,244.14z M351.988,288c-11.058,0-20.053-8.951-20.053-20.016 c0-11.157,8.995-20.106,20.053-20.106c11.146,0,20.148,8.949,20.148,20.106C372.137,279.049,363.134,288,351.988,288z M351.988,200.19c-11.058,0-20.053-8.993-20.053-20.083c0-11.094,8.995-20.107,20.053-20.107c11.146,0,20.148,9.014,20.148,20.107 C372.137,191.197,363.134,200.19,351.988,200.19z M395.947,244.14c-11.105,0-20.101-9.019-20.101-20.107 c0-11.09,8.995-20.104,20.101-20.104c11.059,0,20.053,9.014,20.053,20.104C416,235.121,407.006,244.14,395.947,244.14z"></path> </g> </IconBase>; } };IosGameControllerB.defaultProps = {bare: false}
src/components/TopBar.js
dkadrios/zendrum-stompblock-client
import React from 'react' import PropTypes from 'prop-types' import { withStyles, AppBar, Toolbar, SvgIcon, Typography } from '@material-ui/core' import UserInfo from './UserInfo' import ZendrumLogo from '../images/ZendrumLogo.svg.js' import RestompAd from './RestompAd' const styles = { title: { flex: 1, fontFamily: 'Armalite-Rifle', fontSize: '42px', fontWeight: 'normal', marginLeft: '4px', }, icon: { width: 45, height: 45, }, toolbar: { paddingLeft: '8px', }, } const TopBar = ({ classes }) => ( <AppBar position="static"> <Toolbar className={classes.toolbar}> <SvgIcon className={classes.icon}> <ZendrumLogo /> </SvgIcon> <Typography type="title" color="inherit" className={classes.title} > STOMPBLOCK </Typography> <RestompAd /> <div> <UserInfo /> </div> </Toolbar> </AppBar> ) TopBar.propTypes = { classes: PropTypes.object.isRequired } export default withStyles(styles)(TopBar)
src/components/custom-drawer-content.js
Doko-Demo-Doa/CSClient-RN
/** * @flow */ 'use strict'; import React from 'react'; import { View, Image, Alert } from 'react-native'; import { NavigationActions } from 'react-navigation'; import { Body, Icon, Left, ListItem, Text } from 'native-base'; import { connect } from 'react-redux'; import md5 from 'blueimp-md5'; import { requestLogout } from '../actions/actions-users'; const CustomDrawerContent = props => { const { logout, user } = props; const { dispatch } = props.navigation; const closeDrawer = NavigationActions.navigate({ routeName: 'DrawerClose', }); const goToScreen = screenName => { const navigateAction = NavigationActions.navigate({ routeName: screenName, }); dispatch(closeDrawer); setTimeout(() => dispatch(navigateAction), 700); }; const onPressLogout = () => { Alert.alert( 'Clip-sub', 'You will be logged out, are you sure?', [ { text: 'OK', onPress: () => logout() }, { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel', }, ], { cancelable: false }, ); dispatch(NavigationActions.navigate({ routeName: 'DrawerClose' })); }; const userItem = !user ? ( <ListItem icon onPress={() => goToScreen('Auth')}> <Left> <Icon name="person" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Login / Register</Text> </Body> </ListItem> ) : ( <ListItem icon onPress={() => goToScreen('Profile')}> <Left> <Icon name="person" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Profile</Text> </Body> </ListItem> ); return ( <View style={drawerStyle.drawerMenuContainer}> <View style={drawerStyle.drawerHeader}> <View style={drawerStyle.miniProfile}> <Image source={ user ? { uri: 'https://gravatar.com/avatar/' + md5(user.email) + '?s=200', } : require('../assets/default_avatar.png') } style={{ width: 90, height: 90, borderRadius: 45, zIndex: 9 }} /> <Text suppressHighlighting style={{ color: '#fff' }}> {user ? user.nickname : ''} </Text> <Text style={{ fontSize: 10, color: '#fff' }}> {user ? user.email : ''} </Text> </View> </View> <ListItem icon onPress={() => dispatch(closeDrawer)}> <Left> <Icon name="home" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Home</Text> </Body> </ListItem> {userItem} <ListItem icon style={{ alignSelf: 'flex-end' }} onPress={() => goToScreen('Preference')} > <Left> <Icon name="ios-construct-outline" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Settings (soon)</Text> </Body> </ListItem> {user && user.id !== null ? ( <ListItem icon onPress={() => onPressLogout()}> <Left> <Icon name="ios-exit-outline" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Log out</Text> </Body> </ListItem> ) : null} </View> ); }; const drawerStyle = { drawerMenuContainer: { backgroundColor: '#fff9f9', flex: 1, alignSelf: 'stretch', flexDirection: 'column', }, drawerHeader: { height: 160, backgroundColor: '#fe686a', }, miniProfile: { position: 'absolute', left: 18, bottom: 12, }, itemText: { fontFamily: 'Hoefler Text', color: '#706b6b', }, }; const mapStateToProps = state => { const { user } = state; return { user, }; }; const mapDispatchToProps = dispatch => { return { logout: () => { return dispatch(requestLogout()); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)( CustomDrawerContent, );
docs/src/components/Typography/Typography.js
seekinternational/seek-asia-style-guide
import React from 'react'; import { Helmet } from 'react-helmet'; import PropTypes from 'prop-types'; import { PageBlock, Card, Section, Paragraph, Text, TextLink, Strong, Positive, Critical, Secondary } from 'seek-asia-style-guide/react'; import { ScreenReaderOnly } from 'seek-asia-style-guide/react'; import Demo from '../Demo/Demo'; import textDemoSpec from 'seek-asia-style-guide/react/Text/Text.demo'; const BackgroundContainer = ({ component: DemoComponent, componentProps }) => ( <PageBlock> <Section style={{ maxWidth: 720 }}> <DemoComponent {...componentProps} /> </Section> </PageBlock> ); BackgroundContainer.propTypes = { component: PropTypes.any, componentProps: PropTypes.object.isRequired }; const loremIpsum = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit,', 'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'Ut convallis elit convallis, bibendum mauris et, lacinia mi.', 'Pellentesque quis arcu dignissim nibh tempor placerat et et lorem.' ].join('\n'); const loremIpsumShort = `${loremIpsum.split(',')[0]}.`; const pageTitle = 'Typography - SEEK Asia Style Guide'; export default () => ( <div> <ScreenReaderOnly> <h1>{pageTitle}</h1> </ScreenReaderOnly> <Helmet> <title>{pageTitle}</title> </Helmet> <PageBlock> <Section header> <Text screaming>Typography</Text> </Section> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>Since typography forms the backbone of our design language, we have a suite of responsive typographical components to support semantic usage of our type hierarchy.</Text> </Paragraph> <Paragraph> <Text>The core typographical building block is the &ldquo;Text&rdquo; component, which renders a block-level span element with a single grid row below it, to leave room for descenders.</Text> </Paragraph> <Paragraph> <Text>It accepts a wide range of options, which can be seen below.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ ...textDemoSpec, title: null }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>To better understand these options, let's step through them one by one.</Text> </Paragraph> </Section> <Section> <Text shouting>Standard Text</Text> <Paragraph> <Text>By default, when no options are provided, standard text is rendered.</Text> </Paragraph> <Paragraph> <Text>Standard text is 14px over 2 grid rows on desktop, and 18px over 3 grid rows on mobile.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { children: loremIpsum }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Weight Variants</Text> <Paragraph> <Text>While all elements in our type hierarchy include a default weight, you can also override these with the provided weight variants.</Text> </Paragraph> </Section> <Section> <Text shouting>Strong Text</Text> <Paragraph> <Text>Any text element can be explicity marked as strong with the &ldquo;strong&rdquo; property, which also causes the element to render a &ldquo;strong&rdquo; tag.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { strong: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>In cases where only a portion of a text block should be marked as strong, a &ldquo;Strong&rdquo; component is provided.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Strong>strong.</Strong>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Regular Text</Text> <Paragraph> <Text>Any text element can be explicity set to regular weight with the &ldquo;regular&rdquo; property.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, regular: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Light Text</Text> <Paragraph> <Text>Finally, any text element can be explicity set to light weight with the &ldquo;light&rdquo; property.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, light: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Tone Variants</Text> <Paragraph> <Text>All text is rendered in our standard neutral shade of black by default, but sometimes text needs to be displayed with different tones.</Text> </Paragraph> </Section> <Section> <Text shouting>Positive Text</Text> <Paragraph> <Text>Any text element can be explicity marked as positive with the &ldquo;positive&rdquo; property or the inline &ldquo;Positive&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { positive: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { superstandard: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Positive>positive.</Positive>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Critical Text</Text> <Paragraph> <Text>Any text element can be explicity marked as critical with the &ldquo;critical&rdquo; property or the inline &ldquo;Critical&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { critical: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Critical>critical.</Critical>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Secondary Text</Text> <Paragraph> <Text>Any text element can be explicity marked as secondary with the &ldquo;secondary&rdquo; property or the inline &ldquo;Secondary&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { secondary: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Secondary>secondary.</Secondary>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Text Links</Text> <Paragraph> <Text>To create a standard text-based link, a &ldquo;TextLink&rdquo; component is provided.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is a ', <TextLink href="#">link</TextLink>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Disabling Baseline</Text> <Paragraph> <Text>By default, all text is adjusted to sit correctly on baseline using <TextLink href="https://github.com/michaeltaranto/basekick">basekick</TextLink>.</Text> </Paragraph> <Paragraph> <Text>In some cases, when text needs to be vertically centred within a container, this isn&rsquo;t the desired behaviour. To deal with this, you can optionally disable the baseline adjustment.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, baseline: false, children: loremIpsumShort }, options: [] }} /> </div> );
src/components/SummaryDetail/SummaryDetail.js
propertybase/react-lds
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { ButtonIcon, IconButton } from '../Button'; const SummaryDetail = ({ children, containerClassName, iconButtonClassName, isOpen, onOpen, renderTitle, title, }) => ( <div className={cx('slds-summary-detail', { 'slds-is-open': isOpen })}> {onOpen && ( <IconButton onClick={onOpen} className={cx('slds-m-right_x-small', iconButtonClassName)} > <ButtonIcon className="slds-summary-detail__action-icon" icon="switch" sprite="utility" /> </IconButton> )} <div className={cx(containerClassName)}> <div className="slds-summary-detail__title"> {renderTitle(title)} </div> {children && ( <div aria-hidden={!isOpen} className="slds-summary-detail__content"> {children({ isOpen })} </div> )} </div> </div> ); SummaryDetail.defaultProps = { children: null, containerClassName: null, iconButtonClassName: null, isOpen: false, onOpen: null, renderTitle: title => ( <h3 className="slds-text-heading_small slds-truncate"> {title} </h3> ), }; SummaryDetail.propTypes = { /** * Function that renders the content. Takes { isOpen } as arguments */ children: PropTypes.func, /** * Additional className for container */ containerClassName: PropTypes.string, /** * Additional className for the expand icon */ iconButtonClassName: PropTypes.string, /** * Whether the content is expanded */ isOpen: PropTypes.bool, /** * Triggered on open icon and title click */ onOpen: PropTypes.func, /** * Renders custom title markup if provided. Receives title as an argument */ renderTitle: PropTypes.func, /** * Title to be used by the renderTitle function */ title: PropTypes.string.isRequired, }; export default SummaryDetail;
src/components/texts/subtitle-text.js
tuantle/hypertoxin
/** * Copyright 2016-present Tuan Le. * * Licensed under the MIT License. * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.html * * 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. * *------------------------------------------------------------------------ * * @module SubtitleText * @description - Subtitle text component. * * @author Tuan Le ([email protected]) * * * @flow */ 'use strict'; // eslint-disable-line import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import PropTypes from 'prop-types'; import { Text as AnimatedText } from 'react-native-animatable'; import { DefaultTheme, DefaultThemeContext } from '../../themes/default-theme'; const DEFAULT_ANIMATION_DURATION_MS = 300; const DEFAULT_SUBTITLE_TEXT_STYLE = DefaultTheme.text.font.subtitle; const readjustStyle = (newStyle = { shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, indentation: 0, color: `themed` }, prevAdjustedStyle = DEFAULT_SUBTITLE_TEXT_STYLE, Theme = DefaultTheme) => { const { shade, alignment, decoration, font, indentation, color, style } = newStyle; const themedShade = shade === `themed` ? Theme.text.subtitle.shade : shade; let themedColor; if (color === `themed`) { if (Theme.text.color.subtitle.hasOwnProperty(Theme.text.subtitle.color)) { themedColor = Theme.text.color.subtitle[Theme.text.subtitle.color][themedShade]; } else { themedColor = Theme.text.subtitle.color; } } else if (Theme.text.color.subtitle.hasOwnProperty(color)) { themedColor = Theme.text.color.subtitle[color][themedShade]; } else { themedColor = color; } return { small: { ...prevAdjustedStyle.small, ...Theme.text.font.subtitle.small, fontFamily: font === `themed` ? Theme.text.font.subtitle.small.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, normal: { ...prevAdjustedStyle.normal, ...Theme.text.font.subtitle.normal, fontFamily: font === `themed` ? Theme.text.font.subtitle.normal.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, large: { ...prevAdjustedStyle.large, ...Theme.text.font.subtitle.large, fontFamily: font === `themed` ? Theme.text.font.subtitle.large.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) } }; }; export default class SubtitleText extends React.Component { static contextType = DefaultThemeContext static propTypes = { exclusions: PropTypes.arrayOf(PropTypes.string), room: PropTypes.oneOf([ `none`, `content-left`, `content-middle`, `content-right`, `content-bottom`, `content-top`, `media`, `activity-indicator` ]), shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]), alignment: PropTypes.oneOf([ `left`, `center`, `right` ]), decoration: PropTypes.oneOf([ `none`, `underline`, `line-through` ]), size: PropTypes.oneOf([ `themed`, `small`, `normal`, `large` ]), font: PropTypes.string, indentation: PropTypes.number, uppercased: PropTypes.bool, lowercased: PropTypes.bool, color: PropTypes.string, initialAnimation: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ refName: PropTypes.string, transitions: PropTypes.arrayOf(PropTypes.shape({ to: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), from: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), option: PropTypes.shape({ duration: PropTypes.number, delay: PropTypes.number, easing: PropTypes.string }) })), onTransitionBegin: PropTypes.func, onTransitionEnd: PropTypes.func, onAnimationBegin: PropTypes.func, onAnimationEnd: PropTypes.func }) ]) } static defaultProps = { exclusions: [ `` ], room: `none`, shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, size: `themed`, indentation: 0, uppercased: false, lowercased: false, color: `themed`, initialAnimation: `themed` } static getDerivedStateFromProps (props, state) { const { shade, alignment, decoration, font, indentation, color, style } = props; const { Theme } = state.context; return { adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, state.adjustedStyle, Theme) }; } constructor (props) { super(props); const component = this; component.refCache = {}; component.state = { context: { Theme: DefaultTheme }, adjustedStyle: DEFAULT_SUBTITLE_TEXT_STYLE }; } animate (animation = { onTransitionBegin: () => null, onTransitionEnd: () => null, onAnimationBegin: () => null, onAnimationEnd: () => null }) { const component = this; const { Theme } = component.context; if (typeof animation === `string` && animation !== `none`) { const animationName = animation.replace(/-([a-z])/g, (match, word) => word.toUpperCase()); if (Theme.text.animation.subtitle.hasOwnProperty(animationName)) { animation = Theme.text.animation.subtitle[animationName]; } } if (typeof animation === `object`) { const { refName, transitions, onTransitionBegin, onTransitionEnd, onAnimationBegin, onAnimationEnd } = animation; const componentRef = component.refCache[refName]; if (componentRef !== undefined && Array.isArray(transitions)) { let transitionDuration = 0; const transitionPromises = transitions.map((transition, transitionIndex) => { let transitionBeginPromise; let transitionEndPromise; if (typeof transition === `object`) { let transitionType; let componentRefTransition = { from: {}, to: {} }; let componentRefTransitionOption = { duration: DEFAULT_ANIMATION_DURATION_MS, delay: 0, easing: `linear` }; if (transition.hasOwnProperty(`from`)) { let from = typeof transition.from === `function` ? transition.from(component.props, component.state, component.context) : transition.from; componentRefTransition.from = typeof from === `object` ? from : {}; transitionType = `from`; } if (transition.hasOwnProperty(`to`)) { let to = typeof transition.to === `function` ? transition.to(component.props, component.state, component.context) : transition.to; componentRefTransition.to = typeof to === `object` ? to : {}; transitionType = transitionType === `from` ? `from-to` : `to`; } if (transition.hasOwnProperty(`option`) && typeof transition.option === `object`) { componentRefTransitionOption = { ...componentRefTransitionOption, ...transition.option }; } transitionBeginPromise = new Promise((resolve) => { setTimeout(() => { if (transitionType === `to`) { componentRef.transitionTo( componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing, componentRefTransitionOption.delay ); } else if (transitionType === `from-to`) { setTimeout(() => { componentRef.transition( componentRefTransition.from, componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing ); }, componentRefTransitionOption.delay); } (typeof onTransitionBegin === `function` ? onTransitionBegin : () => null)(transitionIndex); resolve((_onTransitionBegin) => (typeof _onTransitionBegin === `function` ? _onTransitionBegin : () => null)(_onTransitionBegin)); }, transitionDuration + 5); }); transitionDuration += componentRefTransitionOption.duration + componentRefTransitionOption.delay; transitionEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onTransitionEnd === `function` ? onTransitionEnd : () => null)(transitionIndex); resolve((_onTransitionEnd) => (typeof _onTransitionEnd === `function` ? _onTransitionEnd : () => null)(transitionIndex)); }, transitionDuration); }); } return [ transitionBeginPromise, transitionEndPromise ]; }); const animationBeginPromise = new Promise((resolve) => { (typeof onAnimationBegin === `function` ? onAnimationBegin : () => null)(); resolve((_onAnimationBegin) => (typeof _onAnimationBegin === `function` ? _onAnimationBegin : () => null)()); }); const animationEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onAnimationEnd === `function` ? onAnimationEnd : () => null)(); resolve((_onAnimationEnd) => (typeof _onAnimationEnd === `function` ? _onAnimationEnd : () => null)()); }, transitionDuration + 5); }); return Promise.all([ animationBeginPromise, ...transitionPromises.flat(), animationEndPromise ].filter((animationPromise) => animationPromise !== undefined)); } } } componentDidMount () { const component = this; const { shade, alignment, decoration, font, indentation, color, initialAnimation, style } = component.props; const { Theme } = component.context; component.setState((prevState) => { return { context: { Theme }, adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, prevState.adjustedStyle, Theme) }; }, () => { if ((typeof initialAnimation === `string` && initialAnimation !== `none`) || typeof initialAnimation === `object`) { component.animate(initialAnimation); } }); } componentWillUnMount () { const component = this; component.refCache = {}; } render () { const component = this; const { size, uppercased, lowercased, children } = component.props; const { adjustedStyle } = component.state; const { Theme } = component.context; const themedSize = size === `themed` ? Theme.text.subtitle.size : size; let contentChildren = null; if (React.Children.count(children) > 0) { contentChildren = React.Children.toArray(React.Children.map(children, (child) => { if (uppercased) { return child.toUpperCase(); } else if (lowercased) { return child.toLowerCase(); } return child; })); } return ( <AnimatedText ref = {(componentRef) => { component.refCache[`animated-text`] = componentRef; }} style = { adjustedStyle[themedSize] } ellipsizeMode = 'tail' numberOfLines = { 1 } useNativeDriver = { true } > { contentChildren } </AnimatedText> ); } }
pages/error/index.js
koistya/react-static-boilerplate
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import history from '../../core/history'; import Link from '../../components/Link'; import s from './styles.css'; class ErrorPage extends React.Component { static propTypes = { error: React.PropTypes.object, }; componentDidMount() { document.title = this.props.error && this.props.error.status === 404 ? 'Page Not Found' : 'Error'; } goBack = event => { event.preventDefault(); history.goBack(); }; render() { if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console const [code, title] = this.props.error && this.props.error.status === 404 ? ['404', 'Page not found'] : ['Error', 'Oups, something went wrong']; return ( <div className={s.container}> <main className={s.content}> <h1 className={s.code}>{code}</h1> <p className={s.title}>{title}</p> {code === '404' && <p className={s.text}> The page you're looking for does not exist or an another error occurred. </p> } <p className={s.text}> <a href="/" onClick={this.goBack}>Go back</a>, or head over to the&nbsp; <Link to="/">home page</Link> to choose a new direction. </p> </main> </div> ); } } export default ErrorPage;
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/StateUninitialized.js
facebook/flow
// @flow import React from 'react'; class MyComponent extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
jiuzhou/RootScene.js
Cowboy1995/JZWXZ
/** * Created by Tong on 2017/5/10. */ /** * Copyright (c) 2017-present, Liu Jinyong * All rights reserved. * * https://github.com/huanxsd/MeiTuan * @flow */ //import liraries import React, { Component } from 'react'; import { Text, StyleSheet, View, TextInput, TouchableOpacity, ToastAndroid, Dimensions, Image, Button }from 'react-native'; import { StackNavigator,TabNavigator,TabBarBottom } from 'react-navigation'; import screen from './common/screen'; import color from './common/color'; import TabBarItem from './common/TabBarItem'; import Login from './page/RegisterLogin/Login'; import Register from './page/RegisterLogin/Register'; import SMSLogin from './page/RegisterLogin/SMSLogin'; import SetPassword from './page/RegisterLogin/SetPassword'; import HomeScene from './page/Home/HomeScene'; import WikiScene from './page/Wiki/WikiScene'; import MomentsScene from './page/Moments/MomentsScene'; import MineScene from './page/Mine/MineScene'; class YinDao extends Component { static navigationOptions = ({ navigation }) => ({ header:null, }); render() { const { navigate } = this.props.navigation; return ( <View> <TouchableOpacity onPress={() => navigate('Login')}> <Image source={require('./img/yindao.jpg')} style={styles.yindao} /> </TouchableOpacity> <Image source={require('./img/yindao.jpg')} style={styles.yindao} /> </View> ) } } class MyNotificationsScreen extends Component { render() { return ( <Button onPress={() => this.props.navigation.goBack()} title="Go back home" /> ); } } const styles = StyleSheet.create({ icon: { width: 26, height: 26, }, yindao: { height:screen.height, width:screen.width, }, }); const MyApp = TabNavigator({ Home: { screen: HomeScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '主页', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/[email protected]')} selectedImage={require('./img/[email protected]')} /> ) }), }, Wiki: { screen: WikiScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '百科', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/[email protected]')} selectedImage={require('./img/[email protected]')} /> ) }), }, Moments: { screen: MomentsScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '朋友圈', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/[email protected]')} selectedImage={require('./img/[email protected]')} /> ) }), }, Mine: { screen: MineScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '我的', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/[email protected]')} selectedImage={require('./img/[email protected]')} /> ) }), }, }, { tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', swipeEnabled: true, animationEnabled: true, lazy: true, tabBarOptions: { activeTintColor: color.theme, inactiveTintColor: '#979797', style: { backgroundColor: '#ffffff' }, }, } ); const Navigator = StackNavigator( { MyApp:{ screen:MyApp }, Home:{ screen:YinDao }, Login:{ screen:Login }, Register:{ screen:Register }, SMSLogin:{ screen:SMSLogin }, SetPassword:{ screen:SetPassword }, // Tab: { screen: Tab }, }, { navigationOptions: { // headerStyle: { backgroundColor: color.theme } headerBackTitle: null, headerTintColor: '#333333', showIcon: true, }, } ); const prevGetStateForAction = Navigator.router.getStateForAction; Navigator.router.getStateForAction = (action, state) => { // Do not allow to go back from Login if (action.type === "Navigation/BACK" && state && state.routes[state.index].routeName === "Login") { return null; } if (action.type === "Navigation/BACK" && state && state.routes[state.index].routeName === "MyApp") { return null; } // Do not allow to go back to Login // if (action.type === "Navigation/BACK" && state) { // const newRoutes = state.routes.filter(r => r.routeName !== "Login"); // const newIndex = newRoutes.length - 1; // return prevGetStateForAction(action, { index: newIndex, routes: newRoutes }); // } // return prevGetStateForAction(action, state); }; //make this component available to the app export default Navigator;
modules/RouteUtils.js
littlefoot32/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { var type = element.type var route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * var routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { var routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
react-ui/src/Navbar.js
Swoodend/pollster-heroku
import React, { Component } from 'react'; import NavbarNotLoggedIn from './NavbarNotLoggedIn'; import NavbarLoggedIn from './NavbarLoggedIn'; class Navbar extends Component { constructor(props){ super(props); this.state = { loggedIn : false } } componentWillMount(){ let user = localStorage.getItem("currentUser"); if (user){ this.setState({ loggedIn:user }); } } render(){ console.log('rendering nav', this.state); let nav = this.state.loggedIn ? <NavbarLoggedIn username={this.state.loggedIn}/> : <NavbarNotLoggedIn/> return ( <div> {nav} </div> ); } } export default Navbar;
src/components/common/icons/Open.js
WendellLiu/GoodJobShare
import React from 'react'; /* eslint-disable */ const Open = (props) => ( <svg {...props} width="148" height="148" viewBox="0 0 148 148"> <g transform="translate(41.625 46.25)"> <polygon points="27.75 0 27.75 60.125 37 60.125 37 0"/> <polygon points="62.438 25.438 2.313 25.438 2.313 34.688 62.438 34.688"/> </g> </svg> ); /* eslint-enable */ export default Open;
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch02/02_07/start/src/index.js
yevheniyc/C
import React from 'react' import { render } from 'react-dom' import { hello, goodbye } from './lib' render( <div> {hello} {goodbye} </div>, document.getElementById('react-container') )
pages/nintama.js
ybiquitous/next-todo
import React from 'react' const QUESTIONS = [ { image: 'http://www.line-tatsujin.com/stamp/outline/a00227-0.png', choices: [ '猪名寺乱太郎', '猪奈寺乱太郎', '猪名寺乱太朗', ], correct: 0, }, { image: 'http://neoapo.com/images/character/13006/a4de7d3b0dcadf1d1e9a5fd51f8fe9b5.png', choices: [ '摂子きり丸', '摂津きり丸', '説津きり丸', ], correct: 1, }, { image: 'http://neoapo.com/images/character/13007/bbd72bb531cb56e884bd53c1ae454807.png', choices: [ '福富しんべえ', '副富しんべえ', '福富しんべヱ', ], correct: 2, }, ] export default class extends React.Component { constructor(props) { super(props) this.state = { questions: QUESTIONS.map(q => ({ ...q, answered: false })), } this.handleClick = this.handleClick.bind(this) this.renderQuestion = this.renderQuestion.bind(this) } handleClick(index) { const { questions } = this.state const question = questions[index] question.answered = true this.setState({ questions }) } renderQuestion({ image, imageAlt, choices, correct, answered }, index) { return ( <div className="block" key={index}> <div> <img src={image} alt={imageAlt} /> </div> <div> {choices.map((choice, i) => ( <p key={choice} className={correct === i && 'correct'} data-answered={answered}> <input type="radio" name={`question${index}`} id={`question${index}-${i}`} /> <label htmlFor={`question${index}-${i}`}>{i + 1}. {choice}</label> </p> ))} <p> <span onClick={() => this.handleClick(index)} role="button" tabIndex="0">正解は?</span> </p> </div> <style jsx>{` .block { display: flex; font-size: 2rem; margin: 2rem 0; } img { width: 200px; } input[type="radio"] { margin: 0 2em; } [role="button"] { color: blue; } [role="button"]:hover { cursor: pointer; } strong { color: red; font-size: 1.5em; margin-left: 1em; } .correct[data-answered="true"] { border: 0.2em solid red; } `}</style> </div> ) } render() { return ( <div> {this.state.questions.map(this.renderQuestion)} </div> ) } }
react-flux-mui/js/material-ui/src/svg-icons/editor/format-quote.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatQuote = (props) => ( <SvgIcon {...props}> <path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/> </SvgIcon> ); EditorFormatQuote = pure(EditorFormatQuote); EditorFormatQuote.displayName = 'EditorFormatQuote'; EditorFormatQuote.muiName = 'SvgIcon'; export default EditorFormatQuote;
src/svg-icons/notification/confirmation-number.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
main.js
manojadd/bob-demo
import React from 'react'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Bob from './components/Bob.jsx'; import ProjectDetails from './components/ProjectDetails.jsx'; import {Router,Route,IndexRoute,hashHistory} from 'react-router'; import Feedback from './components/Feedback.jsx'; import Header from './components/Header.jsx'; import Login from './components/Login.jsx'; import cookie from "react-cookie"; import LayoutComponent from './components/LayoutComponent.jsx'; import {cyan500,cyan50,indigo700,grey900,grey600,white,red,fullBlack, cyan700, pinkA200,grey100, grey300, grey400, grey500, darkBlack,} from 'material-ui/styles/colors'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import {fade} from 'material-ui/utils/colorManipulator'; import muiThemeable from 'material-ui/styles/muiThemeable'; const muiTheme = getMuiTheme({ palette: { primary1Color: indigo700, primary2Color: cyan700, primary3Color: grey400, accent1Color: pinkA200, accent2Color: grey100, accent3Color: grey500, textColor: darkBlack, alternateTextColor: white, canvasColor: white, borderColor: grey300, disabledColor: fade(darkBlack, 0.3), pickerHeaderColor: cyan500, clockCircleColor: fade(darkBlack, 0.07), shadowColor: fullBlack, } }); function checkAuth(nextState,replace){ //console.log(cookie.load("Token")); if(cookie.load("Token")==undefined) { replace({ pathname: '/' }) } } function checkLoggedIn(nextState,replace){ //console.log(cookie.load("Token")); if(cookie.load("Token")!=undefined) { replace({ pathname: 'bob' }) } } ReactDOM.render( <MuiThemeProvider muiTheme={muiTheme}> <div> <Router history={hashHistory}> <Route path = '/' component={Header}> <IndexRoute component={Login} onEnter={checkLoggedIn}/> <Route path='/project' component={ProjectDetails} onEnter={checkAuth}/> <Route path='/bob' component={Bob} onEnter={checkAuth}/> <Route path='/notification' component={LayoutComponent} onEnter={checkAuth}/> <Route path='/feedback' component={Feedback}/> </Route> </Router> </div> </MuiThemeProvider>, document.getElementById('root') );
example/index.android.js
line64/react-native-checkout-mercadopago
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; import * as MercadoPago from 'react-native-checkout-mercadopago'; import env from './app.json'; export default class Example extends React.Component { state = { status: null }; handleClick = async () => { try { const payment = await MercadoPago.startCheckout(env['public_key'], env['preference_id']); this.setState({ status: JSON.stringify(payment) }); } catch (error) { this.setState({ status: error.toString() }); } }; render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native MercadoPago Checkout </Text> <Text style={styles.instructions}> Tap the following button to start the checkout flow </Text> <TouchableHighlight onPress={this.handleClick}> <Text style={styles.button}> CHECKOUT PRODUCT FOR $100 </Text> </TouchableHighlight> <Text> {this.state.status} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, button: { backgroundColor: 'blue', color: 'white', padding: 10 } }); AppRegistry.registerComponent('example', () => Example);
src/containers/app/AppBase.js
mikebarkmin/react-to-everything
import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; import theme from '../../theme/theme'; import Header from '../../components/header/Header'; import Navigation from '../../components/navigation/Navigation'; injectTapEventPlugin(); const styles = { content: { maxWidth: 800, margin: '0 auto', }, }; export default class Base extends React.Component { render() { return ( <MuiThemeProvider muiTheme={getMuiTheme(theme)}> <div> <Header /> <Navigation /> <div style={styles.content}> {this.renderRoute()} </div> </div> </MuiThemeProvider> ); } } Base.propTypes = { children: React.PropTypes.element, };
client/src/containers/LandingPage/index.js
pqmcgill/stamp-wedding-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import detectWebpSupport from '../../util/detectWebpSupport'; import CompatibleImg from '../../components/CompatibleImg'; import { css } from 'aphrodite'; import { Grid, Row, Col } from 'react-flexbox-grid-aphrodite'; import styles from './styles'; import Quiz from '../Quiz'; import { startQuiz } from '../../actions/quiz'; import Paper from 'material-ui/Paper'; import smoothscroll from 'smoothscroll'; const contextTypes = { router: React.PropTypes.object }; export class App extends Component { constructor (props, context) { super(props, context); this.linkTo = this.linkTo.bind(this); } linkTo (path) { this.context.router.transitionTo(path); } render() { const parallaxStyles = detectWebpSupport() ? css(styles.parallax, styles.parallaxWebp) : css(styles.parallax, styles.parallaxJpg); return ( <div className={ css(styles.wrapper) }> <div className={ css(styles.content) }> <div className={ css(styles.antiWrapper) }> <Grid fluid> <Row center="xs"> <Col> <CompatibleImg imgName="flower1" fallback="png" className={ css(styles.flower, styles.img) } /> </Col> </Row> <Row center="xs" middle="xs"> <Col xs={12} className={ css(styles.info) + ' quicksandLight' } onClick={ this.linkTo.bind(null, '/info') } > <h2 className={ css(styles.infoHeader) + ' quicksandRegular' }>June 10, 2017 4:30pm</h2> </Col> </Row> <Row center="xs"> <Col xs={6}> <CompatibleImg imgName="flower2" fallback="png" data-aos="fade-right" data-aos-offset="300" className={ css(styles.flower, styles.flower2, styles.img) } /> </Col> </Row> </Grid> </div> </div> <div className={ parallaxStyles }> </div> <Paper zDepth={3}> <div className={ css(styles.quizWrapper) } onClick={ this.props.startQuiz }> <Grid fluid className={ css(styles.quizLink) + ' quicksandMedium' }> <Row center="xs"> <Col id="startQuiz" xs={12}> Think you know Sam and Pat? Take the quiz to find out! </Col> </Row> </Grid> </div> </Paper> <Quiz /> </div> ); } } App.contextTypes = contextTypes; const mapDispatchToProps = dispatch => { return { startQuiz() { dispatch(startQuiz()); setTimeout(() => { smoothscroll(document.getElementById('startQuiz')); }, 100); } }; }; export default connect(() => ({}), mapDispatchToProps)(App);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js
liamhu/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(users) { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, ...users, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load([{ id: 42, name: '42' }]); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-spread"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
examples/with-loading/pages/index.js
sedubois/next.js
import React from 'react' import Header from '../components/Header' export default () => ( <div> <Header /> <p>Hello Next!</p> </div> )
pages/index.js
jubearsun/innovative-design
import anime from 'animejs'; import React from 'react'; import classNames from 'classnames'; import DocumentTitle from 'react-document-title'; import FontAwesome from 'react-fontawesome'; import KeyHandler, { KEYDOWN } from 'react-key-handler'; import { prefixLink } from 'gatsby-helpers'; import _ from 'lodash'; import Logo, { LOGO_TEXT, LOGO_ICON } from './components/logo'; import Typing from './components/typing'; const DISPLAY_NONE = 'none'; const DISPLAY_BLOCK = 'block'; const sectionTitles = [ 'home', 'about', 'tiers', 'decals' ]; const numOfSections = sectionTitles.length; let slideAnimations = {}; let slideAnimationsOut = {}; function generateSlideAnimations(win) { slideAnimations = { slide0: [ { targets: '.splash__container', translateX: [win.innerWidth, 0], delay: 25, easing: "easeOutCirc", duration: 400 }, { targets: '.slide__button--wrapper', translateX: [-win.innerWidth, 0], delay: 50, easing: "easeOutCirc", duration: 400 } ], slide1: [ { targets: '.circle--one', scale: [0, 1], delay: 25, easing: "easeOutCirc", duration: 275 }, { targets: '.circle--two', scale: [0, 1], delay: 110, easing: "easeOutCirc", duration: 275 }, { targets: '.circle--three', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 275 }, { targets: '.info__container--circles', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 275 } ], slide2: [ { targets: '.blue', scale: [0, 1], delay: 50, easing: "easeOutCirc", duration: 200 }, { targets: '.gold', scale: [0, 1], delay: 100, easing: "easeOutCirc", duration: 200 }, { targets: '.photo', scale: [0, 1], delay: 150, easing: "easeOutCirc", duration: 200 }, { targets: '.web', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 200 }, { targets: '.video', scale: [0, 1], delay: 250, easing: "easeOutCirc", duration: 200 }, { targets: '.info__container--icons', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 250 } ], slide3: [ { targets: '.decal--intro', scale: [0, 1], delay: 25, easing: "easeOutCirc", duration: 275 }, { targets: '.decal--gdp', scale: [0, 1], delay: 110, easing: "easeOutCirc", duration: 275 }, { targets: '.decal--photo', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 275 }, { targets: '.decal__container--decals', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 275 } ] }; slideAnimationsOut = { slide0: [ { targets: '.splash__container', translateX: [0, -win.innerWidth], delay: 25, easing: "linear", duration: 400 }, { targets: '.slide__button--wrapper', translateX: [0, win.innerWidth], delay: 50, easing: "linear", duration: 400 } ], slide1: [ { targets: '.circle--one', scale: [1, 0], delay: 25, easing: "linear", duration: 250 }, { targets: '.circle--two', scale: [1, 0], delay: 110, easing: "linear", duration: 250 }, { targets: '.circle--three', scale: [1, 0], delay: 200, easing: "linear", duration: 250 }, { targets: '.info__container--circles', translateY: [0, win.innerHeight], delay: 25, easing: "linear", duration: 250 } ], slide2: [ { targets: '.blue', scale: [1, 0], delay: 50, easing: "linear", duration: 200 }, { targets: '.gold', scale: [1, 0], delay: 100, easing: "linear", duration: 200 }, { targets: '.photo', scale: [1, 0], delay: 150, easing: "linear", duration: 200 }, { targets: '.web', scale: [1, 0], delay: 200, easing: "linear", duration: 200 }, { targets: '.video', scale: [1, 0], delay: 250, easing: "linear", duration: 200 }, { targets: '.decal__container--decals', translateY: [0, win.innerHeight], delay: 50, easing: "linear", duration: 250 } ], slide3: [ { targets: '.decal--intro', scale: [1, 0], delay: 25, easing: "linear", duration: 250 }, { targets: '.decal--gdp', scale: [1, 0], delay: 110, easing: "linear", duration: 250 }, { targets: '.decal--photo', scale: [1, 0], delay: 200, easing: "linear", duration: 250 }, { targets: '.info__container--circles', translateY: [0, win.innerHeight], delay: 25, easing: "linear", duration: 250 } ] }; } export default class Index extends React.Component { constructor(props) { super(props); this.state = { previousIndex: 0, slideIndex: 0 }; } componentDidMount() { if (window) { generateSlideAnimations(window); } this.refs.slide1.style.display = DISPLAY_NONE; this.refs.slide2.style.display = DISPLAY_NONE; } componentDidUpdate() { const slideInName = `slide${this.state.slideIndex}`; const slideOutName = `slide${this.state.previousIndex}`; const animations = slideAnimations[slideInName]; const outAnimations = slideAnimationsOut[slideOutName]; if (outAnimations) { for (let animation of outAnimations) { anime(animation); } } setTimeout(() => { this.refs[slideOutName].style.display = DISPLAY_NONE; this.refs[slideInName].style.display = DISPLAY_BLOCK; if (animations) { for (let animation of animations) { anime(animation); } } }, 500); } _handleKeyboardArrows(e, increment) { this._handleArrowClick(e, increment); } _handleArrowClick(e, increment) { e.preventDefault(); const currentIndex = this.state.slideIndex; const nextIndex = increment ? (currentIndex + 1) : (currentIndex - 1) this.setState({ previousIndex: currentIndex, slideIndex: nextIndex < 0 ? numOfSections - 1 : nextIndex % numOfSections }); } _handleDotsClick(e, index) { e.preventDefault(); if (index != this.state.slideIndex) { this.setState({ previousIndex: this.state.slideIndex, slideIndex: index }); } } render () { const stringsToType = [ 'Design', 'Graphic Design', 'Photography', 'Web Design', 'Videography', 'Design' ]; const navDots = _.map(sectionTitles, (title, idx) => { return ( <li key={ `dots-${idx}` } className="dot" onClick={ (e) => { this._handleDotsClick(e, idx); } } > <div className="dot__tooltip" > { title } </div> <div className={ classNames('circle', { 'circle--active': this.state.slideIndex === idx }) } > </div> </li> ); }); return ( <DocumentTitle title="Innovative Design"> <div> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowDown" onKeyHandle={(e) => { this._handleKeyboardArrows(e, true); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowUp" onKeyHandle={(e) => { this._handleKeyboardArrows(e, false); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowRight" onKeyHandle={(e) => { this._handleKeyboardArrows(e, true); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowLeft" onKeyHandle={(e) => { this._handleKeyboardArrows(e, false); }} /> <div className="page__wrapper home"> <div className="slideshow"> <div ref="slide0" className={ classNames( "slide__layout", "slide__layout--1", { "slide__layout--selected": this.state.slideIndex === 0 } ) } > <div className="splash__container"> <Logo logoType={ LOGO_TEXT } logoClass={ 'logo__svg--color' } /> <Typing defaultString="Design" strings={ stringsToType } interval={ { letter: 50, string: 500 } } backspace={ true } cursor={ '|' } startDelay={ 750 } hideCursorOnDone={ true } /> </div> <div className="slide__button--wrapper"> <div className="slide__button slide__button--1" style={{ backgroundImage: `url("${prefixLink('/img/club-one.jpg')}")` }} ></div> <a href="http://makeberkeleybeautiful.com" target="_blank"> <div className="slide__button slide__button--2"> <div className="apply__text">portfolio</div> <div className="slide__fill"></div> </div> </a> </div> </div> <div ref="slide1" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--2", { "slide__layout--selected": this.state.slideIndex === 1 } ) } > <div className="circle__container"> <div className="circle circle--one" style={{ backgroundImage: `url("${prefixLink('/img/calday.jpg')}")` }} ></div> <div className="circle circle--two" style={{ backgroundImage: `url("${prefixLink('/img/marketing.png')}")` }} ></div> <div className="circle circle--three" style={{ backgroundImage: `url("${prefixLink('/img/flyers.png')}")` }} ></div> </div> <div className="info__container--circles"> Innovative Design is a family of graphic and web designers, photographers, and videographers at the University of California, Berkeley. We are creative individuals who are continuously evolving by collaborating, inspiring and educating one another. </div> </div> <div ref="slide2" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--3", { "slide__layout--selected": this.state.slideIndex === 2 } ) } > <div className="icons__container"> <div className="icon blue" style={{ backgroundImage: `url("${prefixLink('/img/tiers/blue.png')}")` }} ></div> <div className="icon gold" style={{ backgroundImage: `url("${prefixLink('/img/tiers/gold.png')}")` }} ></div> <div className="icon photo" style={{ backgroundImage: `url("${prefixLink('/img/tiers/photo.png')}")` }} ></div> <div className="icon web" style={{ backgroundImage: `url("${prefixLink('/img/tiers/web.png')}")` }} ></div> <div className="icon video" style={{ backgroundImage: `url("${prefixLink('/img/tiers/video.png')}")` }} ></div> </div> <div className="info__container--icons"> <p> Innovative Design has five tiers that students can apply to be a member on: Blue, Gold, Photo, Video, and Web. </p> <p> There are two design tiers, Gold and Blue Tier. <b>Blue Tier</b> is a group of intermediate to advanced designers that offers design services to off-campus groups while <b>Gold Tier</b> offers graphic design education and experience for beginner to intermediate designers to on-campus groups. </p> <p> <b>Photo Tier</b> is a hands-on experience in shooting professional headshots, event photography, stock photos and more. </p> <p> <b>Web Tier</b> works for clients that are in need of technical help in designing their websites. Tier members learn new skills and put existing knowledge to use through hands-on experience. </p> <p> <b>Video Tier</b> creates video campaigns for clients on and off campus -- everything from logo animations, event recap videos and Kickstarter campaigns. </p> <p> Visit <b><a href="http://makeberkeleybeautiful.com" target="_blank">makeberkeleybeautiful.com</a></b> for a full portfolio. </p> </div> </div> <div ref="slide3" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--4", { "slide__layout--selected": this.state.slideIndex === 3 } ) } > <div className="decal__container"> <div className="decal decal--intro" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/intro.png')}")` }} ></div> <div className="decal decal--gdp" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/gdp.png')}")` }} ></div> <div className="decal decal--photo" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/photo.png')}")` }} ></div> </div> <div className="decal__container--decals"> <p> Innovative Design also teaches 3 decals separate from the club that are open to the public. You can register for these decals at the beginning of each semester at <b><a href="http://decal.berkeley.edu" target="_blank">decal.berkeley.edu</a></b>. Infosessions are mandatory, so check our <b>Events</b> tab or like us on Facebook for details and updates. </p> <p> <b>Intro to Photoshop and Illustrator</b> teaches graphic design through the use of Adobe Illustrator and Photoshop. This class is built for students who do not have any prior experience or knowledge of these programs. </p> <p> <b>Graphic Design Principles</b> is a technical course in which students are taught extensive knowledge of Adobe programs (such as Illustrator and/or Photoshop). The class also covers conceptual and theoretical aspects of design such as color theory, branding, and user interface design. </p> <p> <b>Photography Principles</b> is for students interested in learning photography. We start off with the basics (camera manipulations and shooting in RAW) and quickly move onto composition rules and tricks to get better, more thought out photos, and from there move onto how to be a professional photographer, photo ethics, and integrating art into photography. </p> <p> You can take a look at lessons and homework for each of these decals in the <b>Decal Students</b> tab above. </p> </div> </div> </div> <div className="slideshow__nav"> <div className="slideshow__dots"> <ul className="dots"> { navDots } </ul> </div> <div className="slideshow__arrows"> <div className="arrow arrow--left" onClick={(e) => { this._handleArrowClick(e, false) }} > <div className="text">back</div> <div className="arrow__triangle"></div> </div> <div className="arrow arrow--right" onClick={(e) => { this._handleArrowClick(e, true) }} > <div className="text">next</div> <div className="arrow__triangle"></div> </div> </div> </div> </div> </div> </DocumentTitle> ); } }
webapp/app/components/RestoreHistory/index.js
EIP-SAM/SAM-Solution-Server
// // Page history save // import React from 'react'; import { PageHeader } from 'react-bootstrap'; import RestoreHistoryButtons from 'containers/RestoreHistory/Buttons'; import RestoreHistoryTable from 'containers/RestoreHistory/Table'; import styles from 'components/RestoreHistory/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class RestoreHistory extends React.Component { componentDidMount() { const username = window.location.pathname.split('/')[2]; this.props.getHistoryRestoresByUserRequest(username); } render() { let username = ''; if (this.props.userIsAdmin) { username = <PageHeader className={styles.title}><small>{window.location.pathname.split('/')[2]}</small></PageHeader>; } return ( <div> <PageHeader>Restore</PageHeader> {username} <RestoreHistoryButtons /> <RestoreHistoryTable /> </div> ); } } RestoreHistory.propTypes = { userIsAdmin: React.PropTypes.bool, getHistoryRestoresByUserRequest: React.PropTypes.func, };
src/react/JSONTree/JSONArrow.js
josebalius/redux-devtools
import React from 'react'; const styles = { base: { display: 'inline-block', marginLeft: 0, marginTop: 8, marginRight: 5, 'float': 'left', transition: '150ms', WebkitTransition: '150ms', MozTransition: '150ms', borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTopWidth: 5, borderTopStyle: 'solid', WebkitTransform: 'rotateZ(-90deg)', MozTransform: 'rotateZ(-90deg)', transform: 'rotateZ(-90deg)' }, open: { WebkitTransform: 'rotateZ(0deg)', MozTransform: 'rotateZ(0deg)', transform: 'rotateZ(0deg)' } }; export default class JSONArrow extends React.Component { render() { let style = { ...styles.base, borderTopColor: this.props.theme.base0D }; if (this.props.open) { style = { ...style, ...styles.open }; } return <div style={style} onClick={this.props.onClick}/>; } }
source/containers/App/Header/ChatButton.js
mikey1384/twin-kle
import PropTypes from 'prop-types'; import React from 'react'; import Button from 'components/Button'; import Icon from 'components/Icon'; ChatButton.propTypes = { chatMode: PropTypes.bool, loading: PropTypes.bool, numUnreads: PropTypes.number, onClick: PropTypes.func.isRequired }; export default function ChatButton({ onClick, chatMode, loading, numUnreads = 0, ...props }) { const newMessages = !chatMode && numUnreads > 0; return ( <Button {...props} transparent={!newMessages} color={newMessages ? 'gold' : 'black'} onClick={onClick} disabled={loading} > {!loading && !chatMode && <Icon icon="comments" />} {loading && <Icon icon="spinner" pulse />} <span style={{ marginLeft: chatMode ? '0.7rem' : '0.8rem' }}>Talk</span> </Button> ); }
src/Parser/Hunter/Marksmanship/Modules/Items/MKIIGyroscopicStabilizer.js
enragednuke/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; /** * Equip: Your Aimed Shot grants you gyroscopic stabilization, increasing the critical strike chance of your next Aimed Shot by 15% and making it castable while moving. */ class MKIIGyroscopicStabilizer extends Analyzer { static dependencies = { combatants: Combatants, }; usedBuffs = 0; on_initialized() { this.active = this.combatants.selected.hasHands(ITEMS.MKII_GYROSCOPIC_STABILIZER.id); } on_byPlayer_removebuff(event) { const buffId = event.ability.guid; if (buffId !== SPELLS.GYROSCOPIC_STABILIZATION.id) { return; } this.usedBuffs += 1; } item() { return { item: ITEMS.MKII_GYROSCOPIC_STABILIZER, result: <Wrapper>This allowed you to move while casting {this.usedBuffs} <SpellLink id={SPELLS.AIMED_SHOT.id} />s throughout the fight, these <SpellLink id={SPELLS.AIMED_SHOT.id} />s also had 15% increased crit chance.</Wrapper>, }; } } export default MKIIGyroscopicStabilizer;
src/svg-icons/action/assignment-returned.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentReturned = (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-1zm0 15l-5-5h3V9h4v4h3l-5 5z"/> </SvgIcon> ); ActionAssignmentReturned = pure(ActionAssignmentReturned); ActionAssignmentReturned.displayName = 'ActionAssignmentReturned'; ActionAssignmentReturned.muiName = 'SvgIcon'; export default ActionAssignmentReturned;
src/parser/rogue/subtlety/modules/core/NightbladeDuringSymbols.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import DamageTracker from 'parser/shared/modules/AbilityTracker'; import SymbolsDamageTracker from './SymbolsDamageTracker'; class NightbladeDuringSymbols extends Analyzer { static dependencies = { damageTracker: DamageTracker, symbolsDamageTracker: SymbolsDamageTracker, }; constructor(...args) { super(...args); this.symbolsDamageTracker.subscribeInefficientCast( [SPELLS.NIGHTBLADE], (s) => `Try to refresh Nightblade before Symbols of Death` ); } get thresholds() { const total = this.damageTracker.getAbility(SPELLS.NIGHTBLADE.id); const filtered = this.symbolsDamageTracker.getAbility(SPELLS.NIGHTBLADE.id); return { actual: filtered.casts, isGreaterThan: { minor: total.casts/10, average: total.casts/5, major: total.casts, }, style: 'number', }; } suggestions(when) { when(this.thresholds).isGreaterThan(0) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Do not refresh <SpellLink id={SPELLS.NIGHTBLADE.id} /> during <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} /> - cast <SpellLink id={SPELLS.EVISCERATE.id} /> instead. You can refresh <SpellLink id={SPELLS.NIGHTBLADE.id} /> early to make sure that its up for the full duration of <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} />. </>) .icon(SPELLS.NIGHTBLADE.icon) .actual(`You refreshed Nightblade ${actual} times during Symbols of Death.`) .recommended(`${recommended} is recommended`); }); } } export default NightbladeDuringSymbols;
src/universal/modules/auth/signup/components/Signup/Signup.js
ruffers9/django-react-boilerplate
import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Paper from 'material-ui/Paper'; import { Link } from 'react-router-dom'; import '../../../styles/auth.scss'; const validate = values => { const errors = {} if (!values.username) { errors.username = 'Required'; } else if (values.username.length > 15) { errors.username = 'Must be 15 characters or less'; } if (!values.password) { errors.password = 'Required'; } else if (values.password !== values.passwordAgain) { errors.password = 'Passwords do not match'; } if (!values.passwordAgain) { errors.passwordAgain = 'Required'; } return errors } const renderField = ({ input, label, type, meta: { touched, error } }) => ( <TextField {...input} floatingLabelText={label} errorText={touched && error ? error : null} type={type} /> ); const renderAsyncError = statusText => { if (statusText) { return ( <div className="asyncError">{statusText}</div> ); } }; const Signup = props => { const { handleSubmit, pristine, submitting, username, password, statusText } = props; return ( <MuiThemeProvider> <div> <Paper className="formContainer"> <h4 className="form-banner">Signup</h4> <form className="form" onSubmit={e => handleSubmit(e, username, password)}> {renderAsyncError(statusText)} <Field name="username" type="text" component={renderField} label="Username"/> <Field name="password" type="password" component={renderField} label="Password"/> <Field name="passwordAgain" type="password" component={renderField} label="Password (Again)"/> <RaisedButton className="formButton" type="submit" primary={true} label="Submit" disabled={pristine || submitting} /> </form> </Paper> <p className="help-text">Already have an account? <Link to='/login'>Login</Link></p> </div> </MuiThemeProvider> ); } // Decorate the form component export default reduxForm({ form: 'signup', // a unique name for this form validate })(Signup);
packages/react-router-website/modules/components/Logo.js
justjavac/react-router-CN
import React from 'react' import { Block, Row } from 'jsxstyle' import { DARK_GRAY } from '../Theme' import LogoImage from '../logo.png' const Logo = ({ size = 230, shadow = true }) => ( <Row background={DARK_GRAY} width={size+'px'} height={size+'px'} alignItems="center" justifyContent="center" borderRadius="50%" boxShadow={shadow ? `2px ${size/20}px ${size/5}px hsla(0, 0%, 0%, 0.35)` : null} > <Block position="relative" top="-4%" textAlign="center" width="100%"> <img src={LogoImage} width="75%"/> </Block> </Row> ) export default Logo
examples/todomvc/config/react.js
lore/lore
/** * Configuration file for React * * This file is where you define overrides for the default mounting behavior. */ // import React from 'react'; // import ReactDOM from 'react-dom'; // import { Provider } from 'react-redux'; // import { Router } from 'react-router'; export default { /** * ID of DOM Element the application will be mounted to */ // domElementId: 'root', /** * Generate the root component that will be mounted to the DOM. This * function will be invoked by lore after all hooks have been loaded. */ // getRootComponent: function(lore) { // const store = lore.store; // const routes = lore.router.routes; // const history = lore.router.history; // // return ( // <Provider store={store}> // <Router history={history}> // {routes} // </Router> // </Provider> // ); // }, /** * Mount the root component to the DOM */ // mount: function(Root, lore) { // const config = lore.config.react; // ReactDOM.render(Root, document.getElementById(config.domElementId), cb); // } }
src/routes/home/index.js
quasicrial/quasicrial
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,publishedDate,contentSnippet}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Layout><Home news={data.news} /></Layout>, }; }, };
www/app/components/main_panel/email_section.js
kalikaneko/bitmask-dev
import React from 'react' //import { Button, Glyphicon, Alert } from 'react-bootstrap' import SectionLayout from './section_layout' import Account from 'models/account' import Spinner from 'components/spinner' import bitmask from 'lib/bitmask' export default class EmailSection extends React.Component { static get defaultProps() {return{ account: null }} constructor(props) { super(props) this.state = { status: null } this.openKeys = this.openKeys.bind(this) this.openApp = this.openApp.bind(this) this.openPrefs = this.openPrefs.bind(this) console.log('email constructor') } openKeys() {} openApp() {} openPrefs() {} render () { //let message = null //if (this.state.error) { // // style may be: success, warning, danger, info // message = ( // <Alert bsStyle="danger">{this.state.error}</Alert> // ) //} let button = null if (this.state.status == 'ready') { button = <Button onClick={this.openApp}>Open Email</Button> } return ( <SectionLayout icon="envelope" status="on" button={button}> <h1>inbox: </h1> </SectionLayout> ) } }
src/components/common/AsyncElement.js
ajkhatibi/wheevy
import React from 'react'; import Router from 'react-router'; import { Route, RouteHandler, Link } from 'react-router'; var AsyncElement = { loadedComponent: null, load: function () { if (this.constructor.loadedComponent) {return;} this.bundle((component) => { this.constructor.loadedComponent = component; this.forceUpdate(); }); }, componentDidMount: function () { setTimeout(this.load, 1000); }, render: function () { var Component = this.constructor.loadedComponent; if (Component) { // can't find RouteHandler in the loaded component, so we just grab // it here first. this.props.activeRoute = <RouteHandler/>; return <Component {...this.props}/>; } return this.preRender(); } }; export default AsyncElement;
src/containers/GameOfLifePage.js
svitekpavel/Conway-s-Game-of-Life
import React from 'react'; import { connect } from 'react-redux'; import GameOfLife from '../components/GameOfLife'; import { setEpoch, setSpeed, setEvolutionRunning, } from '../actions/gameOfLifeActions'; import getNextEpoch from '../utils/getNextEpoch'; import createGrid from '../utils/createGrid'; import gridInsertPattern from '../utils/gridInsertPattern'; class GameOfLifePage extends React.Component { constructor(props) { super(props); this.handleStartEvolution = this.handleStartEvolution.bind(this); this.handleStopEvolution = this.handleStopEvolution.bind(this); this.handleChangeSpeed = this.handleChangeSpeed.bind(this); this.handlePatternInsert = this.handlePatternInsert.bind(this); this.handleInsertBeacon = this.handlePatternInsert.bind(this, 'beacon'); this.handleInsertGlider = this.handlePatternInsert.bind(this, 'glider'); this.handleInsertLwss = this.handlePatternInsert.bind(this, 'lwss'); } componentDidMount() { const { dispatch } = this.props; // create grid and insert some nice patterns let epoch = createGrid(38, 30); // add simple glider and one Lightweight spaceship (LWSS) epoch = gridInsertPattern('glider', epoch, 15, 7); epoch = gridInsertPattern('lwss', epoch, 0, 5); // add static blocks to top rows to expose colors [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36].map((i) => { epoch = gridInsertPattern('block', epoch, i, 0); }); // add nice blinkers to the bottom of the grid [0, 4, 8, 12, 16, 20, 24, 28, 32].map((i) => { epoch = gridInsertPattern('blinker2', epoch, i+1, 20); }); // add nice beacons to the very bottom of the grid [0, 6, 12, 18, 24, 30].map((i) => { epoch = gridInsertPattern('beacon', epoch, i+2, 26); }); dispatch(setEpoch(epoch)); } componentWillUnmount() { clearInterval(this.evolutionInterval); } calculateNextEpoch() { const { dispatch, speed, } = this.props; setTimeout(() => { const { evolutionRunning, epoch, } = this.props; const nextEpoch = getNextEpoch(epoch); dispatch(setEpoch(nextEpoch)); if (evolutionRunning) { this.calculateNextEpoch(); } }, speed); } handlePatternInsert(patterName, x, y) { const { epoch, dispatch, } = this.props; const nextEpoch = gridInsertPattern(patterName, epoch, x, y); dispatch(setEpoch(nextEpoch)); } handleStartEvolution() { // start the evolution here const { dispatch } = this.props; dispatch(setEvolutionRunning(true)); this.calculateNextEpoch(); } handleStopEvolution() { const { dispatch } = this.props; dispatch(setEvolutionRunning(false)); clearInterval(this.evolutionInterval); } handleChangeSpeed(event) { const { dispatch } = this.props; const { value } = event.target; dispatch(setSpeed(value)); // restart interval } render() { return ( <GameOfLife epoch={this.props.epoch} speed={this.props.speed} evolutionRunning={this.props.evolutionRunning} onStartEvolution={this.handleStartEvolution} onStopEvolution={this.handleStopEvolution} onChangeSpeed={this.handleChangeSpeed} onGridClick={this.handlePatternInsert} onInsertBeacon={this.handleInsertBeacon} onInsertGlider={this.handleInsertGlider} onInsertLwss={this.handleInsertLwss} /> ); } } GameOfLifePage.propTypes = { epoch: React.PropTypes.array.isRequired, evolutionRunning: React.PropTypes.bool.isRequired, dispatch: React.PropTypes.func.isRequired, }; function mapStateToProps(state) { return { epoch: state.gameOfLife.epoch, evolutionRunning: state.gameOfLife.evolutionRunning, speed: state.gameOfLife.speed, }; } function mapDispatchToProps(dispatch) { return { dispatch: dispatch, }; } export default connect( mapStateToProps, mapDispatchToProps )(GameOfLifePage);
src/component/event-form/index.js
vagabond0079/casehawk-frontend
import React from 'react'; import * as util from '../../lib/util.js'; import './event-form.scss'; class EventForm extends React.Component { constructor(props){ super(props); this.state = props.event ? {...props.event} : {title: '', allDay: false, start: '', end: '', eventType: null, tag: '', notify: false}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } componentWillReceiveProps(props){ if(props.event) this.setState(props.event); } handleChange(e){ let {type, name, value} = e.target; type === 'checkbox' ? e.target.checked === false ? this.setState({[name]: false}) : this.setState({[name]: true}) : type === 'datetime-local' ? this.setState({[name]: new Date(value)}) : this.setState({[name]: value}); } handleSubmit(e){ e.preventDefault(); this.props.onComplete(this.state); } render(){ return ( <form className='event-form' onSubmit={this.handleSubmit} > <p> <label htmlFor='start-date-time'> Start Date/Time: </label> <input type='datetime-local' id='start-date-time' name='start' onInput={this.handleChange} /> </p> <p> <label htmlFor='end-date-time'> End Date/Time: </label> <input type='datetime-local' id='end-date-time' name='end' onInput={this.handleChange} /> </p> <p> <input placeholder='Title' type='text' name='title' onChange={this.handleChange} value={this.state.name} /> </p> <p> <label htmlFor='allday'> All Day: </label> <input type='checkbox' id='allday' name='allDay' onChange={this.handleChange} /> </p> <select defaultValue="---" id='event-type' name='eventType' onChange={this.handleChange} > <option value="---"> --- </option> <option value="appointment"> Appointment </option> <option value="court-date"> Court Date </option> <option value="deadline"> Deadline </option> <option value="task"> Task </option> </select> <p> <label htmlFor='notify'> Notify: </label> <input type='checkbox' id='notify' name='notify' onChange={this.handleChange} /> </p> <input placeholder='tags' type='text' name='tag' onChange={this.handleChange} /> <p> <button type='submit'> {this.props.buttonText} </button> </p> </form> ); } } export default EventForm;
actor-apps/app-web/src/app/components/Main.react.js
hejunbinlan/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import VisibilityActionCreators from '../actions/VisibilityActionCreators'; import FaviconActionCreators from 'actions/FaviconActionCreators'; import FaviconStore from 'stores/FaviconStore'; import ActivitySection from 'components/ActivitySection.react'; import SidebarSection from 'components/SidebarSection.react'; import ToolbarSection from 'components/ToolbarSection.react'; import DialogSection from 'components/DialogSection.react'; import Favicon from 'components/common/Favicon.react'; //import AppCacheStore from 'stores/AppCacheStore'; //import AppCacheUpdateModal from 'components/modals/AppCacheUpdate.react'; const visibilitychange = 'visibilitychange'; const onVisibilityChange = () => { if (!document.hidden) { VisibilityActionCreators.createAppVisible(); FaviconActionCreators.setDefaultFavicon(); } else { VisibilityActionCreators.createAppHidden(); } }; const getStateFromStores = () => { return { faviconPath: FaviconStore.getFaviconPath() }; }; class Main extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); document.addEventListener(visibilitychange, onVisibilityChange); FaviconStore.addChangeListener(this.onChange); if (!document.hidden) { VisibilityActionCreators.createAppVisible(); } } onChange = () => { this.setState(getStateFromStores()); } render() { //let appCacheUpdateModal; //if (this.state.isAppUpdateModalOpen) { // appCacheUpdateModal = <AppCacheUpdateModal/>; //} return ( <div className="app row"> <Favicon path={this.state.faviconPath}/> <SidebarSection/> <section className="main col-xs"> <ToolbarSection/> <DialogSection/> </section> <ActivitySection/> {/*appCacheUpdateModal*/} </div> ); } } export default requireAuth(Main);
fields/types/datearray/DateArrayFilter.js
joerter/keystone
import React from 'react'; import ReactDOM from 'react-dom'; import moment from 'moment'; import DayPicker from 'react-day-picker'; import { FormField, FormInput, FormRow, FormSelect } from 'elemental'; const PRESENCE_OPTIONS = [ { label: 'At least one element', value: 'some' }, { label: 'No element', value: 'none' }, ]; const MODE_OPTIONS = [ { label: 'On', value: 'on' }, { label: 'After', value: 'after' }, { label: 'Before', value: 'before' }, { label: 'Between', value: 'between' }, ]; var DayPickerIndicator = React.createClass({ render () { return ( <span className="DayPicker-Indicator"> <span className="DayPicker-Indicator__border" /> <span className="DayPicker-Indicator__bg" /> </span> ); }, }); function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, presence: PRESENCE_OPTIONS[0].value, value: moment(0, 'HH').format(), before: moment(0, 'HH').format(), after: moment(0, 'HH').format(), }; } var DateFilter = React.createClass({ displayName: 'DateFilter', propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), presence: React.PropTypes.string, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { format: 'DD-MM-YYYY', filter: getDefaultValue(), value: moment().startOf('day').toDate(), }; }, getInitialState () { return { activeInputField: 'after', month: new Date(), // The month to display in the calendar }; }, componentDidMount () { // focus the text input if (this.props.filter.mode === 'between') { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, selectPresence (presence) { this.updateFilter({ presence }); ReactDOM.findDOMNode(this.refs.input).focus(); }, selectMode (mode) { this.updateFilter({ mode }); if (mode === 'between') { setTimeout(() => { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); }, 200); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, handleInputChange (e) { const { value } = e.target; let { month } = this.state; // Change the current month only if the value entered by the user is a valid // date, according to the `L` format if (moment(value, 'L', true).isValid()) { month = moment(value, 'L').toDate(); } this.updateFilter({ value: value }); this.setState({ month }, this.showCurrentDate); }, setActiveField (field) { this.setState({ activeInputField: field, }); }, switchBetweenActiveInputFields (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; const { activeInputField } = this.state; const send = {}; send[activeInputField] = day; this.updateFilter(send); const newActiveField = (activeInputField === 'before') ? 'after' : 'before'; this.setState( { activeInputField: newActiveField }, () => { ReactDOM.findDOMNode(this.refs[newActiveField]).focus(); } ); }, selectDay (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; this.updateFilter({ value: day }); }, showCurrentDate () { this.refs.daypicker.showMonth(this.state.month); }, renderControls () { let controls; const { field, filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; // DayPicker stuff const modifiers = { selected: (day) => moment(filter.value).isSame(day), }; if (mode.value === 'between') { controls = ( <div> <FormRow> <FormField width="one-half"> <FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} /> </FormField> <FormField width="one-half"> <FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} /> </FormField> </FormRow> <div style={{ position: 'relative' }}> <DayPicker modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.switchBetweenActiveInputFields} /> <DayPickerIndicator /> </div> </div> ); } else { controls = ( <div> <FormField> <FormInput ref="input" placeholder={placeholder} value={moment(filter.value).format(this.props.format)} onChange={this.handleInputChange} onFocus={this.showCurrentDate} /> </FormField> <div style={{ position: 'relative' }}> <DayPicker ref="daypicker" modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.selectDay} /> <DayPickerIndicator /> </div> </div> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0]; return ( <div> <FormSelect options={PRESENCE_OPTIONS} onChange={this.selectPresence} value={presence.value} /> <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} /> {this.renderControls()} </div> ); }, }); module.exports = DateFilter;
src/components/Contentful/Event/presenter.js
ndlib/usurper
// Presenter component for a Event content type from Contentful import React from 'react' import PropTypes from 'prop-types' import typy from 'typy' import 'static/css/global.css' import LibMarkdown from 'components/LibMarkdown' import Link from 'components/Interactive/Link' import Related from '../Related' import Image from 'components/Image' import Librarians from 'components/Librarians' import PageTitle from 'components/Layout/PageTitle' import SearchProgramaticSet from 'components/SearchProgramaticSet' import ServicePoint from '../ServicePoint' import ShareLinks from 'components/Interactive/ShareLinks' import EmailSubscribeBox from 'components/Interactive/EmailSubscribeBox' import OpenGraph from 'components/OpenGraph' import Canonical from 'components/Canonical' import Media from 'components/Media' import RecurringIndicator from './RecurringIndicator' import Presenters from '../../Presenters' import Sponsorships from '../../Sponsorships' import AddToCalendar from 'components/Interactive/AddToCalendar' import InternalLink from '../InternalLink' import PageLink from '../PageLink' import styles from './style.module.css' const PagePresenter = ({ entry }) => { let body = entry.content if (entry.audience) { body += `\n\nOpen to ${typy(entry.audience).safeArray.join(', ')}.` } return ( <article className='container-fluid content-area' itemScope itemType='http://schema.org/Event' itemProp='mainEntity' > {entry.shortDescription && (<meta itemProp='about' content={entry.shortDescription} />)} <meta itemProp='startDate' content={entry.startDate} /> <meta itemProp='endDate' content={entry.endDate} /> <Canonical /> <PageTitle title={entry.title} itemProp='name' /> <OpenGraph title={entry.title} description={entry.shortDescription} image={entry.representationalImage} /> <SearchProgramaticSet open={false} /> <div className='row'> <main className='col-md-8 article'> <div className='event-info'> <div className='event-details'> <div className='event-detail-date' aria-label='Date'> {entry.displayDate} <RecurringIndicator entry={entry} inline /> </div> <div className='event-detail-time' aria-label='Time'> <LibMarkdown>{entry.displayTime}</LibMarkdown> </div> { entry.locationText && ( <div className='event-detail-location' aria-label='Location' itemScope itemType='http://schema.org/Place' itemProp='location' > <LibMarkdown itemProp='address'>{entry.locationText}</LibMarkdown> </div> ) } </div> <div className='event-buttons'> <ShareLinks title={entry.title} /> <AddToCalendar title={entry.title} description={entry.shortDescription} location={entry.locationText} startDate={entry.startDate} endDate={entry.endDate} /> </div> </div> <LibMarkdown itemProp='description'>{body}</LibMarkdown> <Related className='p-resources' title='Resources' showImages={false}>{entry.relatedResources}</Related> <Sponsorships sponsors={entry.sponsors} /> {typy(entry, 'group.eventGroupType').safeString === 'series' && ( <div className={styles.seriesDescription}> <LibMarkdown>{entry.group.eventGroupDescription}</LibMarkdown> <Link to={`/events/series/${entry.group.id}`}>View all events in this series.</Link> </div> )} <Presenters presenters={typy(entry, 'presenters').safeArray} /> </main> <aside className='col-md-4 right'> <Image cfImage={entry.representationalImage} className='cover' itemProp='image' /> <Link to={entry.registrationUrl} className='button callout' hideIfNull>Register for this event</Link> {typy(entry.callOutLinks).safeArray.map(link => link.sys.contentType.sys.id === 'internalLink' ? ( <InternalLink key={link.sys.id} className='button callout' cfEntry={link} /> ) : ( <PageLink key={link.sys.id} className='button callout' cfPage={link} /> ))} <Media data={entry.media} /> <Librarians netids={entry.contactPeople} /> <ServicePoint cfServicePoint={entry.location} showDetails={false} /> <Related className='p-pages' title='Related Pages' showImages={false}>{entry.relatedPages}</Related> <EmailSubscribeBox type='events' htag={2} /> </aside> </div> <Link to='/events' className='viewAllEvents' arrow>View All Library Events</Link> </article> ) } PagePresenter.propTypes = { entry: PropTypes.object.isRequired, } export default PagePresenter
src/components/usershow/UseritemComponent.js
WishTreeGroup/wishtree_web
'use strict'; import React from 'react'; require('styles/usershow/Useritem.sass'); class UseritemComponent extends React.Component { render() { return ( <div className="useritem-component"> <span>{this.props.itemname}</span>{this.props.itemvalue} </div> ); } } UseritemComponent.displayName = 'UsershowUseritemComponent'; // Uncomment properties you need // UseritemComponent.propTypes = {}; // UseritemComponent.defaultProps = {}; export default UseritemComponent;
web/src/client/createRoutes.js
vampolo/react-experiments
import App from './app/app.react'; import Home from './pages/home.react'; import Login from './pages/auth.react'; import Me from './pages/me.react'; import NotFound from './pages/notFound.react'; import React from 'react'; import Todos from './pages/todos.react'; import Sysdig from './pages/sysdig.react'; import {IndexRoute, Route} from 'react-router'; export default function createRoutes(getState) { function requireAuth(nextState, replaceState) { const loggedIn = getState().users.viewer; if (!loggedIn) { replaceState({nextPathname: nextState.location.pathname}, '/login'); } } return ( <Route component={App} path="/"> <IndexRoute component={Home} /> <Route component={Login} path="login" /> <Route component={Me} onEnter={requireAuth} path="me" /> <Route component={Todos} path="todos" /> <Route component={Sysdig} path="sysdig" /> <Route component={NotFound} path="*" /> </Route> ); }