path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
example/src/style.js
romainberger/react-portal-tooltip
import React from 'react' import ToolTip from './../../src' export default class Style extends React.Component { state = { display: false } escape(html) { return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML } getBasicExample() { return { __html: this.escape(`let style = { style: { background: 'rgba(0,0,0,.8)', padding: 20, boxShadow: '5px 5px 3px rgba(0,0,0,.5)' }, arrowStyle: { color: 'rgba(0,0,0,.8)', borderColor: false } } <ToolTip parent="#style-btn" active={true} position="bottom" arrow="center" style={style}> <NicolasCage/> </ToolTip>`) } } showTooltip = () => { this.setState({display: true}) } hideTooltip = () => { this.setState({display: false}) } render() { let style = { style: { background: 'rgba(0,0,0,.8)', padding: 20, boxShadow: '5px 5px 3px rgba(0,0,0,.5)' }, arrowStyle: { color: 'rgba(0,0,0,.8)', borderColor: false } } return ( <div style={{padding: 20}}> <div style={{marginBottom: 20}}> <p>You can provide a <code>style</code> prop to customize some part of the tooltip. You can give it an object with two properties: <code>style</code>, that will be applied to the tooltip itself, and <code>arrowStyle</code> which will be applied to the arrows. The last one is tricky as the arrows are made with borders so it can be painfull to customize. To make it easier, the <code>arrowStyle.color</code> property will change the background color of the arrow and <code>arrowStyle.borderColor</code> its border. To remove completely the border use a falsy value.</p> <p><a href="https://github.com/romainberger/react-portal-tooltip/blob/master/example/src/style.js">Check out this example to see how this one is done</a></p> </div> <div style={{textAlign: 'center'}}> <button className="btn btn-primary" id="style-btn" style={{marginBottom: 20}} onMouseEnter={this.showTooltip} onMouseLeave={this.hideTooltip}>Thanks www.nyan.cat</button> <ToolTip parent="#style-btn" active={this.state.display} position="bottom" arrow="center" style={style}> <img src="http://www.nyan.cat/cats/original.gif" height="168" width="272" /> </ToolTip> </div> <div style={{marginBottom: 20}}> <pre dangerouslySetInnerHTML={this.getBasicExample()}/> </div> </div> ) } }
src/server.js
yinaw/travelBook
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './assets.json'; const server = global.server = express(); const port = process.env.PORT || 5000; server.set('port', port); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '', entry: assets.app.js }; const css = []; const context = { insertCss: styles => css.push(styles._getCss()), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
app/app.js
ptelad/tal-and-aviad-player
import React from 'react'; import { AppRegistry, StyleSheet, View, ActivityIndicator, FlatList } from 'react-native'; import { parseString } from 'react-native-xml2js'; import ItemCard from './components/ItemCard'; import Player from './components/Player'; export default class TalAndAviad extends React.Component { state = { dataLoaded: false, data: null, refresh: false }; componentDidMount() { this._fetchData(); } async _fetchData() { this.setState({refresh: true}); let response = await fetch('http://eco99fm.maariv.co.il/onair/talAndAviadXml.aspx'); let xml = await response.text(); parseString(xml, (err, result) => { if (err) { console.error(err); } else { console.log(result.Segments.Segment); this.setState({ dataLoaded: true, refresh: false, data: result.Segments.Segment }) } }); } _renderItem({item, index}) { return <ItemCard image={item.RecordedProgramsImg[0]} title={item.RecordedProgramsName[0]} url={/(.*\.mp3)/.exec(item.RecordedProgramsDownloadFile[0])[1]} onPress={this._playItem.bind(this)} /> } _playItem(segment) { this.player && this.player.playSegment(segment); } _playerRef(p) { if (p) { this.player = p; } } render() { if (!this.state.dataLoaded) { return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <ActivityIndicator size="large" color="#E91E63"/> </View> ); } return ( <View style={styles.container}> <FlatList syle={styles.list} data={this.state.data} keyExtractor={item => item.Pid[0]} renderItem={this._renderItem.bind(this)} refreshing={this.state.refresh} onRefresh={this._fetchData.bind(this)} /> <Player ref={this._playerRef.bind(this)}/> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', }, list: { flex: 1 } }); AppRegistry.registerComponent('TalAndAviad', () => TalAndAviad);
src/index.js
djstein/modern-react
import createHistory from 'history/createBrowserHistory'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Switch } from 'react-router-dom'; import { ConnectedRouter, routerMiddleware } from 'react-router-redux'; import { createStore, applyMiddleware, compose } from 'redux'; import { createLogger } from 'redux-logger'; import thunk from 'redux-thunk'; import rootReducer from './app/reducers'; import { ThemeProvider } from 'styled-components'; import { Theme } from './styled_components/src'; import { renderRoutes } from './app/routes/RenderRoutes'; import { routes } from './app/routes/routes'; const basename = process.env.NODE_ENV === 'production' ? '/app/' : '/'; const history = createHistory({ basename }); const historyMiddleware = routerMiddleware(history); const loggerMiddleware = createLogger(); const middleware = { historyMiddleware, loggerMiddleware }; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( rootReducer, composeEnhancers(applyMiddleware(...middleware, thunk)) ); // Required by Axios require('es6-promise').polyfill(); ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history} basename={basename}> <ThemeProvider theme={Theme}> <Switch> {renderRoutes(routes)} </Switch> </ThemeProvider> </ConnectedRouter> </Provider>, document.getElementById('app') );
docs/src/pages/components/drawers/PersistentDrawerRight.js
lgollut/material-ui
import React from 'react'; import clsx from 'clsx'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import CssBaseline from '@material-ui/core/CssBaseline'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import InboxIcon from '@material-ui/icons/MoveToInbox'; import MailIcon from '@material-ui/icons/Mail'; const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', }, appBar: { transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginRight: drawerWidth, }, title: { flexGrow: 1, }, hide: { display: 'none', }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, drawerHeader: { display: 'flex', alignItems: 'center', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, justifyContent: 'flex-start', }, content: { flexGrow: 1, padding: theme.spacing(3), transition: theme.transitions.create('margin', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginRight: -drawerWidth, }, contentShift: { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginRight: 0, }, })); export default function PersistentDrawerRight() { const classes = useStyles(); const theme = useTheme(); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <div className={classes.root}> <CssBaseline /> <AppBar position="fixed" className={clsx(classes.appBar, { [classes.appBarShift]: open, })} > <Toolbar> <Typography variant="h6" noWrap className={classes.title}> Persistent drawer </Typography> <IconButton color="inherit" aria-label="open drawer" edge="end" onClick={handleDrawerOpen} className={clsx(open && classes.hide)} > <MenuIcon /> </IconButton> </Toolbar> </AppBar> <main className={clsx(classes.content, { [classes.contentShift]: open, })} > <div className={classes.drawerHeader} /> <Typography paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa sapien faucibus et molestie ac. </Typography> <Typography paragraph> Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a. </Typography> </main> <Drawer className={classes.drawer} variant="persistent" anchor="right" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> <Divider /> <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </Drawer> </div> ); }
app/javascript/mastodon/containers/account_container.js
kirakiratter/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { makeGetAccount } from '../selectors'; import Account from '../components/account'; import { followAccount, unfollowAccount, blockAccount, unblockAccount, muteAccount, unmuteAccount, } from '../actions/accounts'; import { openModal } from '../actions/modal'; import { initMuteModal } from '../actions/mutes'; import { unfollowModal } from '../initial_state'; const messages = defineMessages({ unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, props) => ({ account: getAccount(state, props.id), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow (account) { if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) { if (unfollowModal) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), })); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock (account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(blockAccount(account.get('id'))); } }, onMute (account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, onMuteNotifications (account, notifications) { dispatch(muteAccount(account.get('id'), notifications)); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
frontend/src/pages/logout.js
jjasonclark/GLAD-to-JAM-on-Docker
import React from 'react'; import { Link } from 'react-router-dom'; import LogoutForm from '../components/logout_form'; const Logout = () => ( <div className="App centered"> <div>Logout Page</div> <Link to="/">Back to home</Link> <LogoutForm /> </div> ); export default Logout;
fixtures/kitchensink/src/features/syntax/DestructuringAndAwait.js
altiore/webpack-react
/** * 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'; async function load() { return { users: [ { 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 } = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-destructuring-and-await"> {this.state.users.map(user => ( <div key={user.id}> {user.name} </div> ))} </div> ); } }
mooc_gp/js/Boy.js
xizhouhezai/react-app
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, Button } from 'react-native'; import { StackNavigator } from 'react-navigation'; import NavigationBar from './component/NavigationBar'; class Boy extends Component { render() { return( <View> <NavigationBar title='Boy' style={{backgroundColor:'#F08080'}} /> <Text> Hi! Boy </Text> <Button title="Hi" onPress={() => { this.props.navigation.navigate('Feed'); }} /> </View> ) } } export default Boy;
src/components/Journal/index.js
andywillis/uws
// Dependencies import React from 'react'; import PropTypes from 'prop-types'; // React import Byline from '../Byline'; import Paginator from '../Paginator'; import EntryList from '../EntryList'; // Style import './style.css'; const createByline = ({ type, value }) => { return ( <Byline type={type !== 'page' ? type : 'date'} value={type !== 'page' ? value : ''} /> ); }; const getPaginator = (totalEntries, pageNumber, pageLimit) => { if (totalEntries > pageLimit) { return ( <Paginator totalEntries={totalEntries} pageNumber={pageNumber} pageLimit={pageLimit} /> ); } }; const buildJournal = (props) => { const { entries, links, filter, totalEntries, pageLimit, pageNumber } = props; const isEntry = filter.type === 'entry'; return ( <div> {!isEntry && createByline(filter)} {!isEntry && getPaginator(totalEntries, pageNumber, pageLimit)} <EntryList entries={entries} links={links} filter={filter} totalEntries={totalEntries} /> {!isEntry && getPaginator(totalEntries, pageNumber, pageLimit)} </div> ); }; /** * @function Journal * @param {object} props Component properties * @return {jsx} Component */ const Journal = (props) => { return ( <div className="Journal"> {buildJournal(props)} </div> ); }; export default Journal; // Function proptypes createByline.propTypes = { type: PropTypes.string.isRequired, value: PropTypes.string.isRequired }; buildJournal.propTypes = { entries: PropTypes.arrayOf(PropTypes.any).isRequired, links: PropTypes.arrayOf(PropTypes.any).isRequired, filter: PropTypes.string.isRequired, totalEntries: PropTypes.number.isRequired, pageLimit: PropTypes.number.isRequired, pageNumber: PropTypes.number.isRequired };
src/svg-icons/action/settings-backup-restore.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBackupRestore = (props) => ( <SvgIcon {...props}> <path d="M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9c-4.97 0-9 4.03-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.51 0-2.91-.49-4.06-1.3l-1.42 1.44C8.04 20.3 9.94 21 12 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z"/> </SvgIcon> ); ActionSettingsBackupRestore = pure(ActionSettingsBackupRestore); ActionSettingsBackupRestore.displayName = 'ActionSettingsBackupRestore'; ActionSettingsBackupRestore.muiName = 'SvgIcon'; export default ActionSettingsBackupRestore;
src/index.js
anovelmous-dev-squad/anovelmous-web
import React from 'react'; import ReactDOM from 'react-dom'; import Root from 'containers/Root'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const target = document.getElementById('root'); const node = ( <Root routerHistory={createBrowserHistory()} /> ); ReactDOM.render(node, target);
libraries/mobx/timer-strict/src/index.js
vivaxy/course
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { useStrict } from 'mobx'; import AppState from './AppState'; import App from './App'; import './index.css'; useStrict(true); const appState = new AppState(); render(<App appState={appState} />, document.getElementById('root')); if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; render( <AppContainer> <NextApp appState={appState} /> </AppContainer>, document.getElementById('root'), ); }); }
node_modules/lite-server/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
kylewistrand/IsUWOpen
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
wrappers/html.js
MichaelCereda/michaelcereda.com
import React from 'react' module.exports = React.createClass({ propTypes () { return { router: React.PropTypes.object, } }, render () { const post = this.props.route.page.data return ( <div className="markdown"> <h1 dangerouslySetInnerHTML={{ __html: post.title }} /> <div dangerouslySetInnerHTML={{ __html: post.body }} /> </div> ) }, })
src/components/Assets.js
peragro/peragro-ui
import React from 'react' import Reflux from 'reflux' import { Link } from 'react-router' import auth from '../utils/auth' var AssetStore = require('../stores/AssetStore'); import BreadCrumb from './BreadCrumb' export default React.createClass({ mixins: [Reflux.listenTo(AssetStore, "update")], getInitialState: function() { return { assets: AssetStore.getAssets(), loading: true }; }, componentDidMount: function() { this.listenTo(AssetStore, this.update); }, update: function (assets) { if (!this.isMounted()) { return; } this.setState({ assets: assets, loading: false }); }, render: function() { var token = auth.getToken(); //console.log(this.state.assets); var assets = this.state.assets.map(function(asset, i) { //return <li key={asset.id}><Link to="asset" params={asset}>{asset.subname}</Link></li>; return <ListAsset key={i} asset={asset} />; }); return ( <div className="container-fluid"> <BreadCrumb routes={this.props.routes}/> <div className="row"> <div className="col-xs-4 scrollable"> <ul> {assets} </ul> </div> <div className="col-xs-8 full-calendar"> {this.props.children} </div> </div> </div> ); } }); export const ListAsset = React.createClass({ render: function() { return ( <li className="row one-list-asset" id="msg-one"> <Link to="asset" params={this.props.asset}> <div className="col-xs-1 checkbox"> <label> <input type="checkbox" /> <i className="fa fa-square-o small"></i> </label> </div> <div className="col-xs-9 message-title">{this.props.asset.subname}</div> <div className="col-xs-2 message-date">12/31/13</div> </Link> </li> ); } });
src/components/ConvertedList/ConvertedList.js
ilyagru/react-currency-converter
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchCurrencies } from '../../redux/actions/fetchActions'; import ConvertedRow from '../ConvertedRow'; import './ConvertedList.css'; export class ConvertedList extends Component { componentDidMount() { this.props.fetchData(this.props.selectedCurrency); } render() { let rows; if (this.props.rates !== undefined) { rows = this.props.rates; const currencyValue = this.props.currencyValue; rows = rows.map((row, index) => { const correctRate = (row.rate * (currencyValue !== '' ? currencyValue : 1)).toFixed(3); const change = (row.rate - row.yesterdayRate).toFixed(3); const correctChange = change > 0 ? `+${change}` : change; return ( <ConvertedRow rate={correctRate} currency={row.currency} key={row.currency} change={correctChange} /> ); }); } else { rows = <ConvertedRow /> } return ( <div className='converted-list'> {this.props.error !== undefined && <ConvertedRow hasError={true} rate={this.props.error} />} {rows} </div> ); } } function mapStateToProps(store) { return { ...store.ratesData, selectedCurrency: store.currency.selectedCurrency, currencyValue: store.currency.currencyValue }; } function mapDispatchToProps(dispatch) { return { fetchData: (baseCurrency) => { dispatch(fetchCurrencies(baseCurrency)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(ConvertedList);
src/example/index.js
abobwhite/slate-editor
import React from 'react' import { Router } from 'react-router' import createBrowserHistory from 'history/createBrowserHistory' import { version } from '../../package.json' import Home from './pages/Home' import './index.css' const history = createBrowserHistory() export default () => ( <Router history={history}> <Home title='Nossas - SlateJS Editor' version={version} /> </Router> )
klassify/interface/components/Trainer.js
fatiherikli/klassify
import React, { Component } from 'react'; import Select from 'react-select'; import styles from './Form.module.css'; import store from '../store'; class Trainer extends Component { state = { text: null, label: null, isTrained: false }; componentDidMount() { this.removeListener = store.addListener( this.updateState.bind(this) ); store.fetchLabels(); } updateState() { this.setState({ labels: store.getLabels() }); } componentWillMount() { this.setState({ labels: store.getLabels() }); } componentWillUnmount() { this.removeListener(); } onTextChange(event) { this.setState({ text: event.target.value }); } onLabelChange(label) { this.setState({ label }); } handleSubmit(event) { event.preventDefault(); let {text, label} = this.state; store.train( text, label ).then(() => { this.setState({ isTrained: true }) }); } render() { let {labels, text, label: currentLabel, isTrained} = this.state; let labelOptions = labels.data.map((label) => ({ value: label, label })); return ( <div className={styles.container}> <form className={styles.form}> {isTrained && ( <div className={styles.success}> The text has been successfully trained. </div> )} <label className={styles.label}>Document</label> <textarea className={styles.body} value={text} onChange={this.onTextChange.bind(this)} placeholder={'Text data.'}></textarea> <label className={styles.label}>Label</label> <div className={styles.select}> <Select value={currentLabel} onChange={this.onLabelChange.bind(this)} allowCreate={true} options={labelOptions} className={styles.Select} /> </div> <input type={'submit'} onClick={this.handleSubmit.bind(this)} className={styles.button} value={'Train'} /> </form> </div> ); } } export default Trainer;
website/src/pages/components/home/ValueProps.js
Pop-Code/keystone
import React, { Component } from 'react'; import Container from '../../../../components/Container'; import { Col, Row } from '../../../../components/Grid'; import { compose } from 'glamor'; import theme from '../../../../theme'; import { EntypoLeaf, EntypoShuffle, EntypoImages, EntypoLightBulb, EntypoPencil, EntypoDocuments, EntypoUsers, EntypoPaperPlane, } from 'react-entypo'; const ValueProp = ({ icon, text, title, text2, marginTop }) => { return ( <div {...compose(styles.base, { marginTop })}> <i {...compose(styles.icon_inner)}>{icon}</i> <div {...compose(styles.content)}> <h3 {...compose(styles.title)}>{title}</h3> <p {...compose(styles.text)}>{text}</p> {text2 ? <p {...compose(styles.text)}>{text2}</p> : null} </div> </div> ); }; ValueProp.defaultProps = { marginTop: '3em', }; export default class ValueProps extends Component { render () { return ( <div className={compose(styles.wrap)}> <Container> <div className={compose(styles.preamble)}> <h2 className={compose(styles.heading)}>Get a head-start on the features you need</h2> <p className={compose(styles.subheading)}>KeystoneJS is the easiest way to build database-driven websites, applications and APIs in Node.js.</p> </div> <Row medium="1/2" large="1/4"> <Col> <ValueProp title="Express.js and MongoDB" text="Keystone will configure express - the de facto web server for node.js - for you and connect to your MongoDB database using Mongoose, the leading ODM package." icon={<EntypoLeaf style={styles.icon} />} /> </Col> <Col> <ValueProp title="Dynamic Routes" text="Keystone starts with best practices for setting up your MV* application, and makes it easy to manage your templates, views and routes." icon={<EntypoShuffle style={styles.icon} />} /> </Col> <Col> <ValueProp title="Database Fields" text="IDs, Strings, Booleans, Dates and Numbers are the building blocks of your database. Keystone builds on these with useful, real-world field types like name, email, password, address, image and relationship fields (and more)" icon={<EntypoImages style={styles.icon} />} /> </Col> <Col> <ValueProp title="Auto-generated Admin UI" text="Whether you use it while you're building out your application, or in production as a database content management system, Keystone's Admin UI will save you time and make managing your data easy." icon={<EntypoLightBulb style={styles.icon} />} /> </Col> </Row> <Row medium="1/2" large="1/4"> <Col> <ValueProp title="Simpler Code" text="Sometimes, async code can get complicated to do simple things. Keystone helps keep simple things - like loading data before displaying it in a view - simple." icon={<EntypoPencil style={styles.icon} />} /> </Col> <Col> <ValueProp title="Form Processing" text="Want to validate a form, upload an image, and update your database with a single line? Keystone can do that, based on the data models you've already defined." icon={<EntypoDocuments style={styles.icon} />} /> </Col> <Col> <ValueProp title="Session Management" text="Keystone comes ready out of the box with session management and authentication features, including automatic encryption for password fields." icon={<EntypoUsers style={styles.icon} />} /> </Col> <Col> <ValueProp title="Email Sending" text="Keystone makes it easy to set up, preview and send template-based emails for your application. It also integrates with Mandrill (Mailchimp's excellent transaction email sending service)" icon={<EntypoPaperPlane style={styles.icon} />} /> </Col> </Row> </Container> </div> ); } }; const styles = { wrap: { padding: '4rem 0', borderBottom: `1px solid ${theme.color.gray05}`, }, icon: { width: '42px', height: '42px', fill: theme.color.blue, }, preamble: { textAlign: 'center', }, heading: { fontSize: '2em', }, subheading: { fontSize: '1.25em', color: theme.color.gray50, }, base: { display: 'flex', flexDirection: 'column', }, content: { flexGrow: 1, }, title: { color: 'inherit', margin: '1.25rem 0 0', }, text: { margin: '1rem 0 0', }, };
src/bootstrap.js
serge-14/smartserialapp
import React from 'react'; import ReactDOM from 'react-dom'; import Main from './components/main'; import { compose, createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import reducer from './reducers' import { resetConnection, clearLogs } from './actions' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' import serialport from 'serialport' import {SerialPortWrapper} from './helpers/serialportwrapper' import persistState from 'redux-localstorage' const loggerMiddleware = createLogger() const enhancer = compose( applyMiddleware( thunkMiddleware, loggerMiddleware ), persistState() ) const store = createStore( reducer, enhancer ) const serialPortWrapper = new SerialPortWrapper( { create: (p,o) => new serialport(p, o), parser: serialport.parsers.readline('\n'), list: (x) => serialport.list(x) }, store.dispatch) store.dispatch(resetConnection()) ReactDOM.render(<Provider store={store}><Main serialport={serialPortWrapper}/></Provider>, document.getElementById('app'));
src/svg-icons/communication/call-missed.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallMissed = (props) => ( <SvgIcon {...props}> <path d="M19.59 7L12 14.59 6.41 9H11V7H3v8h2v-4.59l7 7 9-9z"/> </SvgIcon> ); CommunicationCallMissed = pure(CommunicationCallMissed); CommunicationCallMissed.displayName = 'CommunicationCallMissed'; export default CommunicationCallMissed;
Router/router-demo/src/router/AmbiguousMatches.js
imuntil/React
import React from 'react' import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' const AmbiguousDemo = ({match}) => ( <Router basename={match.url}> <div style={{position: 'absolute', width:'100%', height: '200px'}}> <ul> <li><Link to='/about'>About Us</Link></li> <li><Link to="/company">Company</Link></li> <li><Link to="/kim">Kim (dynamic) </Link></li> <li><Link to="/chris">Chris (dynamic) </Link></li> </ul> <hr/> <Switch> <Route path="/about" render={() => <h2>About</h2>} /> <Route path="/company" render={() => <h3>Company</h3>} /> <Route path="/:user" render={({match}) => ( <div> <h3>User: {match.params.user}</h3> </div> )}/> </Switch> </div> </Router> ) export default AmbiguousDemo
src/components/blocks/BlockText.js
m0sk1t/react_email_editor
/* eslint-disable */ import React from 'react'; import { connect } from 'react-redux'; import { stylizeBlock } from '../../actions'; const mapStateToProps = (state) => { return { config: state.tinymce_config }; }; const mapDispatchToProps = (dispatch) => { return { onPropChange: (prop, val, container, elementIndex) => { dispatch(stylizeBlock(prop, val, container, elementIndex)); } }; }; const BlockText = connect( mapStateToProps, mapDispatchToProps )(({ id, config, blockOptions, onPropChange }) => { const initEditable = ()=>{ window.tinymce.init({ ...config, selector: `#id_${id} td.editable`, init_instance_callback: (editor) => { editor.on('change', function (e) { onPropChange('text', e.target.targetElm.innerHTML, false, 0); }); } }) }; return ( <table width="550" cellPadding="0" cellSpacing="0" role="presentation" > <tbody> <tr> <td width="550" className="editable" onClick={() => initEditable()} style={blockOptions.elements[0]} dangerouslySetInnerHTML={{__html: blockOptions?blockOptions.elements[0].text:'empty node'}} > </td> </tr> </tbody> </table> ); }); export default BlockText;
src/imports/ui/admin/components/products/RecommendProductButton.js
hwillson/meteor-recommendation-builder
import React from 'react'; import { Button } from 'react-bootstrap'; import { addRecommendedProduct } from '/imports/api/recommended_products/methods.js'; class RecommendProductButton extends React.Component { constructor(props) { super(props); this.addProductToRecommendedList = this.addProductToRecommendedList.bind(this); } addProductToRecommendedList(event) { if (event) { event.preventDefault(); } const recommendedProduct = { productName: this.props.rowData.productName, variationName: this.props.rowData.variationName, variationId: this.props.rowData.variationId, productImage: this.props.rowData.productImage, }; addRecommendedProduct.call(recommendedProduct); } render() { return ( <Button bsStyle="primary" onClick={this.addProductToRecommendedList}> Recommend </Button> ); } } RecommendProductButton.propTypes = { rowData: React.PropTypes.object, }; export default RecommendProductButton;
src/components/InfoWindowComponent.js
jezzasan/taproom-react
'use strict'; import React from 'react'; class InfoWindowComponent extends React.Component { constructor(props) { super(props); this.state= { active: false }; } _addToCrawl() { this.setState({active: !this.state.active}); } render() { return ( <div className="infowindow-component"> <h1>{this.props.title}</h1> <p>{this.props.address}</p> <a href={"tel:"+ this.props.tel.split(" ").join('-').replace(/\(/g, '').replace(/\)/g, '')}>{this.props.tel}</a> <button className={"btn "+ (this.state.active ? "btn-primary" : "btn-default")} onClick={this._addToCrawl.bind(this)}>Add To Tour</button> </div> ); } } InfoWindowComponent.displayName = 'InfoWindowComponent'; // Uncomment properties you need // InfoWindowComponent.propTypes = {}; // InfoWindowComponent.defaultProps = {}; export default InfoWindowComponent;
app/javascript/mastodon/features/lists/index.js
dwango/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { fetchLists } from '../../actions/lists'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.lists', defaultMessage: 'Lists' }, subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' }, }); const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ lists: getOrderedLists(state), }); export default @connect(mapStateToProps) @injectIntl class Lists extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, lists: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchLists()); } render () { const { intl, shouldUpdateScroll, lists } = this.props; if (!lists) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.lists' defaultMessage="You don't have any lists yet. When you create one, it will show up here." />; return ( <Column icon='list-ul' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> <ScrollableList scrollKey='lists' shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} > {lists.map(list => <ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='list-ul' text={list.get('title')} /> )} </ScrollableList> </Column> ); } }
src/components/Footer/Footer.js
mminutel/upkeep
import React, { Component } from 'react'; import './Footer.css'; class Footer extends Component { render() { return ( <div> --Footer goes here.-- </div> ); } } export default Footer;
src/docs/components/heading/HeadingDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Heading from 'grommet/components/Heading'; import Anchor from 'grommet/components/Anchor'; import Button from 'grommet/components/Button'; import DocsArticle from '../../../components/DocsArticle'; export default class HeadingDoc extends Component { render () { return ( <DocsArticle title='Heading' action={ <Button primary={true} path={`/docs/heading/examples`} label='Examples' /> }> <section> <p>An HTML heading, one of h1, h2, h3, h4, h5, h6. See <Anchor path='/docs/typography'>Typography</Anchor> for examples of all heading tags.</p> <Heading>Sample Heading</Heading> </section> <section> <h2>Properties</h2> <dl> <dt><code>align start|center|end</code></dt> <dd>The horizontal alignment of the Heading. Defaults to <code>start</code>.</dd> <dt><code>margin none|small|medium|large</code></dt> <dd>The vertical margin below the Heading. Defaults to <code>medium</code>.</dd> <dt><code>strong true|false</code></dt> <dd>If the Heading should be bold. Defaults to <code>false</code>.</dd> <dt><code>tag h1|h2|h3|h4|h5|h6</code></dt> <dd>Which HTML heading level should be used. Defaults to <code>h1</code>.</dd> <dt><code>truncate true|false</code></dt> <dd>Restrict the text to a single line and truncate with ellipsis if it is too long to all fit. Defaults to <code>false</code>.</dd> <dt><code>uppercase true|false</code></dt> <dd>Convert the heading to uppercase. Defaults to <code>false</code>.</dd> </dl> </section> </DocsArticle> ); } };
src/js/Containers/Blog.js
7sleepwalker/addicted-to-mnt
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import BlogPost from '../Components/BlogPost'; import { getPosts } from '../Actions/postActions'; class Blog extends Component { componentWillMount() { this.props.dispatch(getPosts()); } render() { let posts = this.props.posts.posts; let postRender; if (posts && posts.length > 0) { posts = posts.filter((value) => { return value.publish !== false; }); postRender = posts.map((item, n) => ( <BlogPost key={n} content={item} postNumber={posts.length - (n + 1)} postsAmount={posts.length}/> )); } return ( <div className="blog"> {postRender ? postRender.reverse() : null} </div> ); } } const mapStateToProps = (store) => { return { posts: store.posts }; }; Blog.props = { posts: PropTypes.shape({ error: PropTypes.string, fetched: PropTypes.bool, fetching: PropTypes.bool, posts: PropTypes.object.isRequired }) }; export default connect(mapStateToProps)(Blog);
examples/js/manipulation/del-row-custom-confirm.js
pvoznyuk/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-console: 0 */ /* eslint no-alert: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); function customConfirm(next, dropRowKeys) { const dropRowKeysStr = dropRowKeys.join(','); if (confirm(`(It's a custom confirm)Are you sure you want to delete ${dropRowKeysStr}?`)) { // If the confirmation is true, call the function that // continues the deletion of the record. next(); } } const options = { handleConfirmDeleteRow: customConfirm }; // If you want to enable deleteRow, you must enable row selection also. const selectRowProp = { mode: 'checkbox' }; export default class DeleteRowCustomComfirmTable extends React.Component { render() { return ( <BootstrapTable data={ products } deleteRow={ true } selectRow={ selectRowProp } options={ options }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
packages/node_modules/@ciscospark/react-component-chip-file/src/index.js
Altocloud/alto-react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon, {ICON_TYPE_DOCUMENT} from '@ciscospark/react-component-icon'; import ChipBase from '@ciscospark/react-component-chip-base'; import styles from './styles.css'; export default function ChipFile(props) { const { name, size, thumbnail, type } = props; let icon; if (!thumbnail) { icon = ( // eslint-disable-line no-extra-parens <div className={classNames(`ciscospark-file-icon`, styles.icon)}> <Icon type={ICON_TYPE_DOCUMENT} /> </div> ); } return ( <ChipBase {...props}> <div className={classNames(`ciscospark-file-thumbnail`, styles.thumbnail)}> {icon} <img alt="" src={thumbnail} /> </div> <div className={classNames(`ciscospark-file-info`, styles.info)}> <div className={classNames(`ciscospark-file-name`, styles.name)}>{name}</div> <div className={classNames(`ciscospark-file-meta`, styles.meta)}> <div className={classNames(`ciscospark-file-size`, styles.size)}>{size}</div> <div className={classNames(`ciscospark-file-type`, styles.type)}>{type}</div> </div> </div> </ChipBase> ); } ChipFile.propTypes = { name: PropTypes.string, size: PropTypes.string, thumbnail: PropTypes.string, type: PropTypes.string };
frontend/app/js/components/card.js
serverboards/serverboards
import React from 'react' import Icon from './iconicon' import {colorize} from 'app/utils' import {MarkdownPreview} from 'react-marked-markdown' /// To be able to change container to <a> or whatever. Normally would be div function Div(props){ return ( <div {...props}> {props.children} </div> ) } function A(props){ return ( <a {...props}> {props.children} </a> ) } function Card(props){ let Container=Div switch(props.container){ case 'a': Container=A break; case 'div': Container=Div break; default: console.warn("Unknown container type for card: %o", props.container) } return ( <Container className={`ui card ${props.className || ""}`} onClick={props.onClick}> <div className="ui attached top"> <Icon icon={props.icon} plugin={props.plugin}/> <div className="right"> {props.tags.map( t => ( <span className="ui text label">{t} <i className={`ui rectangular ${colorize(t)} label`}/></span> ))} </div> </div> <h3 className="ui header">{props.title}</h3> <div className="ui description"><MarkdownPreview value={props.description}/></div> {props.children} </Container> ) } export default Card
examples/huge-apps/routes/Calendar/components/Calendar.js
ksivam/react-router
import React from 'react' class Calendar extends React.Component { render() { const events = [ { id: 0, title: 'essay due' } ] return ( <div> <h2>Calendar</h2> <ul> {events.map(event => ( <li key={event.id}>{event.title}</li> ))} </ul> </div> ) } } export default Calendar
imports/ui/pages/EditDocument.js
lizihan021/SAA-Website
import React from 'react'; import PropTypes from 'prop-types'; import { Meteor } from 'meteor/meteor'; import Documents from '../../api/documents/documents'; import DocumentEditor from '../components/DocumentEditor'; import NotFound from './NotFound'; import container from '../../modules/container'; const EditDocument = ({ doc }) => (doc ? ( <div className="EditDocument"> <h4 className="page-header">Editing "{ doc.title }"</h4> <DocumentEditor doc={ doc }/> </div> ) : <NotFound />); EditDocument.propTypes = { doc: PropTypes.object, }; export default container((props, onData) => { const documentId = props.params._id; const subscription = Meteor.subscribe('documents.view', documentId); if (subscription.ready()) { const doc = Documents.findOne(documentId); onData(null, { doc }); } }, EditDocument);
icon_tab_bar.js
evilgoldfish/North
import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; /** * Modified from the FacebookExample class FacebookTabBar, * from the react-native-scrollable-tab-view repository. * https://github.com/skv-headless/react-native-scrollable-tab-view/blob/master/examples/FacebookTabsExample/FacebookTabBar.js * Copyright 2016 skv-headless. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const IconTabBar = React.createClass({ tabIcons: [], propTypes: { goToPage: React.PropTypes.func, activeTab: React.PropTypes.number, tabs: React.PropTypes.array, }, componentDidMount() { if (this.props.activeTextColor.substring(0,1) !== "#" || this.props.inactiveTextColor.substring(0,1) !== "#") { global.ErrorUtils.reportFatalError({name: "IncompatibleColorTypeError", message: "Non-hex active/inactive text colors are not currently supported in IconTabBar."}); } this._listener = this.props.scrollValue.addListener(this.setAnimationValue); }, setAnimationValue({ value, }) { this.tabIcons.forEach((icon, i) => { const altProgress = (Math.abs(value - i) >= 0 && Math.abs(value - i) <= 1) ? Math.abs(value-i) : 1; const progress = (value - i >= 0 && value - i <= 1) ? value - i : altProgress; icon.setNativeProps({ style: { color: this.iconColor(progress), }, }); }); }, hexToRgb(hex) { // Code taken from StackOverflow answer: http://stackoverflow.com/a/5624139 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }, //color between rgb(59,89,152) and rgb(204,204,204) iconColor(progress) { const active = this.hexToRgb(this.props.activeTextColor); const inactive = this.hexToRgb(this.props.inactiveTextColor); const red = active["r"] + (inactive["r"] - active["r"]) * progress; const green = active["g"] + (inactive["g"] - active["g"]) * progress; const blue = active["b"] + (inactive["b"] - active["b"]) * progress; return `rgb(${red}, ${green}, ${blue})`; }, render() { return <View style={[styles.tabs, this.props.style, {backgroundColor: this.props.backgroundColor, borderTopWidth: (this.props.drawTopBorder === "true") ? 1 : 0}]}> {this.props.tabs.map((tab, i) => { return <TouchableOpacity key={tab} onPress={() => this.props.goToPage(i)} style={styles.tab}> <Icon name={tab} size={30} color={this.props.activeTab === i ? this.props.activeTextColor : this.props.inactiveTextColor} ref={(icon) => { this.tabIcons[i] = icon; }} /> </TouchableOpacity>; })} </View>; }, }); const styles = StyleSheet.create({ tab: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingBottom: 10, }, tabs: { height: 45, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingTop: 5, borderWidth: 1, borderLeftWidth: 0, borderRightWidth: 0, borderBottomColor: 'rgba(0,0,0,0.05)', borderTopColor: 'rgba(0,0,0,0.05)', }, }); export default IconTabBar;
react/react-demo/src/index.js
hunering/demo-code
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Game from './App'; import Clock from "./Clock"; import NameForm from "./NameForm"; import registerServiceWorker from './registerServiceWorker'; //ReactDOM.render(<App />, document.getElementById('root')); ReactDOM.render( <Game />, document.getElementById('root') ); ReactDOM.render( <Clock />, document.getElementById('clock') ); ReactDOM.render( <NameForm />, document.getElementById('nameForm') ); registerServiceWorker();
src/components/login/loginForm/LoginTabs.js
TulevaEE/onboarding-client
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import LoginTab from './LoginTab'; class LoginTabs extends Component { static propTypes = { children: PropTypes.instanceOf(Array).isRequired, }; state = { activeTab: this.props.children[0].props.label, }; onClickTabItem = (tab) => { this.setState({ activeTab: tab }); }; render() { const { onClickTabItem, props: { children }, state: { activeTab }, } = this; return ( <div className="tabs"> <ol className="tab-list"> {React.Children.map(children, (child) => { const { label, hideOnMobile } = child.props; return ( <LoginTab activeTab={activeTab} key={label} label={label} onClick={onClickTabItem} hideOnMobile={hideOnMobile} /> ); })} </ol> <div className="tab-content"> {React.Children.map(children, (child) => { if (child.props.label !== activeTab) { return undefined; } return child.props.children; })} </div> </div> ); } } export default LoginTabs;
src/js/components/input/input_switch.js
rafaelfbs/realizejs
import React from 'react'; import PropTypes from '../../prop_types'; import i18n from '../../i18n'; import { mixin } from '../../utils/decorators'; import InputCheckboxBase from './checkbox/input_checkbox_base'; import InputHidden from './input_hidden'; import { Label } from '../label'; import { CssClassMixin, } from '../../mixins'; @mixin( CssClassMixin, ) export default class InputSwitch extends InputCheckboxBase { static propTypes = { label: PropTypes.string, offLabel: PropTypes.localizedString, onLabel: PropTypes.localizedString, }; static defaultProps = { themeClassKey: 'input.switch', offLabel: 'false', onLabel: 'true', label: null, }; checkboxProps() { if (this.valueIsBoolean()) { return {}; } return this.props; } serialize() { return { [this.props.name]: this.state.checked }; } renderLabel() { if (!this.props.label) { return null; } return <Label name={this.props.label} active />; } renderInputHidden() { if (this.valueIsBoolean()) { return <InputHidden {...this.props} value={this.state.value} />; } return null; } render() { return ( <div> <div className={this.className()}> <label> {i18n.t(this.props.offLabel)} <input {...this.checkboxProps()} checked={this.state.checked} value={this.state.value} disabled={this.props.disabled || this.props.readOnly} className={this.inputClassName()} onChange={this.handleChange} type="checkbox" ref="input" /> <span className="lever"></span> {i18n.t(this.props.onLabel)} </label> {this.renderInputHidden()} </div> {this.renderLabel()} </div> ); } }
src/components/common/cover/Cover/Cover.js
CtrHellenicStudies/Commentary
import React from 'react'; import CoverBackground from '../CoverBackground'; import './Cover.css'; class Cover extends React.Component { constructor(props) { super(props); this.state = { width: window.innerWidth, }; } componentDidMount() { window.addEventListener('resize', () => { this.handleResize(); }); } handleResize() { this.setState({ windowWidth: window.innerWidth, }); } render() { const { className, full, left, bottom, background, reactsToMouse, overlay } = this.props; const classes = [className]; const { windowWidth } = this.state; let height = window.innerHeight * 0.66; if (full) { classes.push('cover--full'); height = window.innerHeight; } if (height < 260) { height = 260; } if (left) { classes.push('cover--left'); } else if (bottom) { classes.push('cover--bottom'); } else { classes.push('cover--center'); } return ( <div className={`cover ${classes.join(' ')}`} style={{ width: windowWidth, height: `${height}px`, }} > <div className="cover-inner" style={{ width: windowWidth }} > { background && <CoverBackground reactsToMouse={reactsToMouse} > {background} </CoverBackground> } { this.props.children && <div className="cover-content"> {this.props.children} </div> } { overlay && <div className="cover-overlay"> {overlay} </div> } </div> </div> ); } } export default Cover;
src/component/Header/index.js
botlang/org.botlang.try
import AppBar from 'material-ui/AppBar'; import Botlang from 'botlang'; import React from 'react'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import { withStyles } from 'material-ui/styles'; const styles = { root: { width: '100%', } }; function Header(props) { const classes = props.classes; return ( <div className={classes.root}> <AppBar position='static' color='primary'> <Toolbar> <Typography type='title' color='inherit'> {`Try Botlang - Online REPL (v${Botlang.version()})`} </Typography> </Toolbar> </AppBar> </div> ); } export default withStyles(styles)(Header);
app/containers/HomePage/index.js
dreamdojo/converter
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import Input from '../Input'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <h1 style={{ textAlign: 'center', paddingTop: 50 }}>Drop it like its haawt</h1> <Input /> </div> ); } }
src/components/NavigationButton.js
meerasahib/meerablog1
import React from 'react'; import styled from 'styled-components'; import Link from 'gatsby-link'; import BackIcon from 'react-icons/lib/fa/chevron-left'; import ForwardIcon from 'react-icons/lib/fa/chevron-right'; import { getColorFromString } from '../utils/color'; import { rhythm } from '../utils/typography'; const StyledLink = styled(Link)` position: absolute; top: 0; background-color: ${props => (props.title ? 'transparent' : 'white')}; color: ${props => (props.title ? 'white' : '#002635')}; text-decoration: none; padding: 0 ${rhythm(1 / 2)}; height: ${rhythm(1.5)}; line-height: 44px; display: flex; align-items: center; justify-content: space-around; transition: all 125ms ease-in-out; text-transform: uppercase; font-family: sans-serif; font-size: ${rhythm(1 / 2)}; z-index: 2; &:hover { background-color: ${props => (props.title ? 'white' : '#002635')}; color: ${props => props.title ? getColorFromString(props.title) : 'white'}; } .wf-active & { font-family: 'Montserrat', sans-serif; } .content { display: none; padding: 0 ${rhythm(1 / 4)}; } .icon { font-size: ${rhythm(3 / 4)}; } @media only screen and (min-width: 768px) { .content { display: inline-block; } } `; const Prev = styled(StyledLink)` left: 0; `; const Next = styled(StyledLink)` right: 0; `; export default function BackButton({ children, to, next, prev, ...rest }) { if (prev) { return ( <Prev to={to} {...rest}> <BackIcon className="icon" /> <span className="content"> {children} </span> </Prev> ); } else if (next) { return ( <Next to={to} {...rest}> <span className="content"> {children} </span> <ForwardIcon className="icon" /> </Next> ); } }
app/src/General/components/NotFound.js
rmonnier/hypertube
import React from 'react'; import { injectIntl } from 'react-intl'; const NotFound = (props) => { const pageNotFound = props.intl.formatMessage({ id: 'general.pageNotFound' }); const noPage = props.intl.formatMessage({ id: 'general.noPage' }); return ( <div className="not-found"> <h1>{pageNotFound}</h1> <p>{noPage}</p> </div> ); }; export default injectIntl(NotFound);
app/m_components/collect/CollectItem.js
kongchun/BigData-Web
import React from 'react'; import { Link } from 'react-router'; class CollectItem extends React.Component { render(){ return ( <Link to={'/article/' + this.props.articleid} className="collect-list-item"> <div className="container container-row"> <div className="row"> <div className="col-sm-8"> <div className="collect-title">{this.props.title}</div> <div className="collect-time">{this.props.time}</div> </div> <div className="col-sm-4"> <div className="collect-thumbnail"><img className="img-responsive" max-height="200" src={this.props.thumbnail} alt="七只狸猫"/></div> </div> </div> </div> </Link>); } } export default CollectItem;
app/containers/Assessments/CreateAssessment.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Formsy from 'formsy-react'; import FRC from 'formsy-react-components'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; import capitalize from 'lodash.capitalize'; import { DEFAULT_YEAR } from 'config'; import { saveNewAssessment, enableSubmitForm, disableSubmitForm, fetchRespondentTypes, fetchSources, toggleCreateAssessmentModal, fetchQuestiongroupTypes, } from '../../actions'; import { Modal } from '../../components/Modal'; import { dateFormat, addYearToCurrentDate } from '../../utils'; import { lastVerifiedYears } from '../../Data'; const { Input, Checkbox, Select } = FRC; class CreateAssessmentForm extends Component { constructor(props) { super(props); this.state = { showRespondentTypes: false, }; this.submitForm = this.submitForm.bind(this); this.handleChange = this.handleChange.bind(this); } componentDidMount() { this.props.fetchSources(); this.props.fetchRespondentTypes(); this.props.fetchQuestiongroupTypes(); } setStartDate() { const formatteddate = dateFormat(new Date()); return formatteddate; } setEndDate() { return dateFormat(addYearToCurrentDate()); } getSources() { return this.props.sources.map((source) => { return { value: source.id, label: capitalize(source.name), }; }); } submitForm() { const myform = this.myform.getModel(); const assessment = { name: myform.assessmentName, group_text: myform.group_text, start_date: myform.startDate, end_date: myform.endDate, version: myform.version, double_entry: myform.doubleEntry, academic_year: myform.academic_year_id, inst_type: myform.inst_type_id, source: myform.source_id, description: myform.description, lang_name: myform.lang_name, comments_required: myform.comments_required, image_required: myform.image_required, respondenttype_required: myform.respondenttype_required, default_respondent_type: myform.default_respondent_type_id, type: myform.type, survey: this.props.programId, status: 'AC', }; this.props.save(assessment); } filterRespondentTypes() { return this.props.respondentTypes.map((type) => { return { value: type.char_id, label: type.name, }; }); } handleChange(field, value) { this.setState({ showRespondentTypes: value, }); } render() { const { showRespondentTypes } = this.state; const { isOpen, canSubmit, error, types } = this.props; const respondentTypes = this.filterRespondentTypes(); const institutionTypes = [ { value: 'primary', label: 'Primary School' }, { value: 'pre', label: 'Pre School' }, ]; const sources = this.getSources(); return ( <Modal title="Create QuestionGroup" contentLabel="Create QuestionGroup" isOpen={isOpen} onCloseModal={this.props.closeModal} canSubmit={canSubmit} submitForm={this.submitForm} cancelBtnLabel="Cancel" submitBtnLabel="Create" > <Formsy.Form id="createAssessment" onValidSubmit={this.submitForm} onValid={this.props.enableSubmitForm} onInvalid={this.props.disabledSubmitForm} ref={(ref) => { this.myform = ref; }} > {!isEmpty(error) ? ( <div className="alert alert-danger"> {Object.keys(error).map((key) => { const value = error[key]; return ( <p key={key}> <strong>{key}:</strong> {value[0]} </p> ); })} </div> ) : ( <span /> )} <Input name="assessmentName" id="assessmentName" value="" label="Name" type="text" placeholder="Please enter the questiongroup name" help="This is a required field" required validations="minLength:1" /> <Input name="lang_name" id="lang_name" value="" label="Name in local language" type="text" validations="minLength:1" /> <Input name="description" id="description" value="" label="Description" type="text" validations="minLength:1" /> <Input name="group_text" id="group_text" value="" label="Group Text" type="text" validations="minLength:1" /> <Input type="date" label="Start Date" value={this.setStartDate()} name="startDate" help="Please select the start date of the questiongroup" required id="startDate" /> <Input type="date" label="End Date" value={this.setEndDate()} help="Please select the end date of the questiongroup" name="endDate" /> <Input name="version" id="version" value="1.0" label="Version" type="text" validations="minLength:1" /> <Select name="type" label="Type" value={get(types[0], 'value')} options={types} required /> <Select name="academic_year_id" label="Academic Year" value={DEFAULT_YEAR || get(lastVerifiedYears[0], 'value')} options={lastVerifiedYears} /> <Select name="inst_type_id" label="Institution Type" value={get(institutionTypes[0], 'value')} options={institutionTypes} required /> <Select name="source_id" label="Source" value={get(sources[0], 'value')} options={sources} required /> {/* <Select name="type_id" label="Survey Type" value={get(surveyTypes[0], 'value')} options={surveyTypes} required /> */} <Checkbox label="Respondent Type Required" name="respondenttype_required" id="respondenttype_required" onChange={this.handleChange} /> <Select name="default_respondent_type_id" label="Default Respondent Type" value={showRespondentTypes ? respondentTypes[0].value : ''} options={showRespondentTypes ? respondentTypes : []} disabled={!showRespondentTypes} /> <Checkbox label="Comments Required" name="comments_required" id="comments_required" /> {/* <Checkbox label="Image Required" name="image_required" id="image_required" /> */} {/* <Checkbox label="Double Entry" name="doubleEntry" id="doubleEntry" help="Check this box if this questiongroup will need double entry" /> */} </Formsy.Form> </Modal> ); } } CreateAssessmentForm.propTypes = { fetchSources: PropTypes.func, sources: PropTypes.array, error: PropTypes.object, isOpen: PropTypes.bool, canSubmit: PropTypes.bool, save: PropTypes.func, enableSubmitForm: PropTypes.func, disabledSubmitForm: PropTypes.func, closeModal: PropTypes.func, fetchRespondentTypes: PropTypes.func, respondentTypes: PropTypes.array, programId: PropTypes.any, types: PropTypes.array, fetchQuestiongroupTypes: PropTypes.func, }; const mapStateToProps = (state) => { const { sources } = state.sources; return { isOpen: state.modal.createAssessment, canSubmit: state.appstate.enableSubmitForm, programId: Number(state.programs.selectedProgram), error: state.assessments.error, respondentTypes: state.respondentTypes.types, sources, types: state.questiongroupTypes.types, }; }; const CreateAssessment = connect(mapStateToProps, { save: saveNewAssessment, enableSubmitForm, disableSubmitForm, closeModal: toggleCreateAssessmentModal, fetchRespondentTypes, fetchSources, fetchQuestiongroupTypes, })(CreateAssessmentForm); export { CreateAssessment };
src/components/Accordion/Accordion.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; import { settings } from 'carbon-components'; const { prefix } = settings; const Accordion = ({ children, className, ...other }) => { const classNames = classnames(`${prefix}--accordion`, className); return ( <ul {...other} className={classNames}> {children} </ul> ); }; Accordion.propTypes = { /** * Pass in the children that will be rendered within the Accordion */ children: PropTypes.node, /** * Specify an optional className to be applied to the container node */ className: PropTypes.string, }; export default Accordion;
src/client/js/app.js
onomatopio/ChatPlayground
// system import React from 'react'; import ReactDOM from 'react-dom'; // user import * as polifills from '../../util/polifills'; import ChatApp from './components/App/ChatApp.react'; ReactDOM.render( <ChatApp />, document.getElementById('react') );
pages/terms-and-conditions.js
turntwogg/final-round
import React from 'react'; import Page from '../components/Page'; import PageHeader from '../components/PageHeader'; import PageContent from '../components/PageContent'; export default () => { return ( <Page title="Terms & Conditions"> <PageHeader title="Terms & Conditions" /> <PageContent> <p> These terms and conditions outline the rules and regulations for the use of Final Round Esports's Website. </p> <p>Final Round Esports is located at:</p> <address> Final Round Esports <br /> 890 Glen Abbey Way <br /> Melbourne FL, 32940 </address> <p> By accessing this website we assume you accept these terms and conditions in full. Do not continue to use Final Round Esports's website if you do not accept all of the terms and conditions stated on this page. </p> <p> The following terminology applies to these Terms and Conditions, Privacy Statement and Disclaimer Notice and any or all Agreements: "Client", "You" and "Your" refers to you, the person accessing this website and accepting the Company's terms and conditions. "The Company", "Ourselves", "We", "Our" and "Us", refers to our Company. "Party", "Parties", or "Us", refers to both the Client and ourselves, or either the Client or ourselves. All terms refer to the offer, acceptance and consideration of payment necessary to undertake the process of our assistance to the Client in the most appropriate manner, whether by formal meetings of a fixed duration, or any other means, for the express purpose of meeting the Client's needs in respect of provision of the Company's stated services/products, in accordance with and subject to, prevailing law of United States. Any use of the above terminology or other words in the singular, plural, capitalisation and/or he/she or they, are taken as interchangeable and therefore as referring to same. </p> <h2>Cookies</h2> <p> We employ the use of cookies. By using Final Round Esports's website you consent to the use of cookies in accordance with Final Round Esports's privacy policy. </p> <p> Most of the modern day interactive web sites use cookies to enable us to retrieve user details for each visit. Cookies are used in some areas of our site to enable the functionality of this area and ease of use for those people visiting. Some of our affiliate / advertising partners may also use cookies. </p> <h2>License</h2> <p> Unless otherwise stated, Final Round Esports and/or it's licensors own the intellectual property rights for all material on Final Round Esports. All intellectual property rights are reserved. You may view and/or print pages from https://www.finalround.gg for your own personal use subject to restrictions set in these terms and conditions. </p> <p>You must not:</p> <ol> <li>Republish material from https://www.finalround.gg</li> <li> Sell, rent or sub-license material from https://www.finalround.gg </li> <li> Reproduce, duplicate or copy material from https://www.finalround.gg </li> </ol> <p> Redistribute content from Final Round Esports (unless content is specifically made for redistribution). </p> <h2>Hyperlinking to our Content</h2> <ol> <li> The following organizations may link to our Web site without prior written approval: <ol> <li>Government agencies;</li> <li>Search engines;</li> <li>News organizations;</li> <li> Online directory distributors when they list us in the directory may link to our Web site in the same manner as they hyperlink to the Web sites of other listed businesses; and </li> <li> Systemwide Accredited Businesses except soliciting non-profit organizations, charity shopping malls, and charity fundraising groups which may not hyperlink to our Web site. </li> </ol> </li> </ol> <ol start="2"> <li> These organizations may link to our home page, to publications or to other Web site information so long as the link: (a) is not in any way misleading; (b) does not falsely imply sponsorship, endorsement or approval of the linking party and its products or services; and (c) fits within the context of the linking party's site. </li> <li> We may consider and approve in our sole discretion other link requests from the following types of organizations: <ol> <li> commonly-known consumer and/or business information sources such as Chambers of Commerce, American Automobile Association, AARP and Consumers Union; </li> <li>dot.com community sites;</li> <li> associations or other groups representing charities, including charity giving sites, </li> <li>online directory distributors;</li> <li>internet portals;</li> <li> accounting, law and consulting firms whose primary clients are businesses; and </li> <li>educational institutions and trade associations.</li> </ol> </li> </ol> <p> We will approve link requests from these organizations if we determine that: (a) the link would not reflect unfavorably on us or our accredited businesses (for example, trade associations or other organizations representing inherently suspect types of business, such as work-at-home opportunities, shall not be allowed to link); (b)the organization does not have an unsatisfactory record with us; (c) the benefit to us from the visibility associated with the hyperlink outweighs the absence of Final Round Esports and (d) where the link is in the context of general resource information or is otherwise consistent with editorial content in a newsletter or similar product furthering the mission of the organization. </p> <p> These organizations may link to our home page, to publications or to other Web site information so long as the link: (a) is not in any way misleading; (b) does not falsely imply sponsorship, endorsement or approval of the linking party and it products or services; and (c) fits within the context of the linking party's site. </p> <p> If you are among the organizations listed in paragraph 2 above and are interested in linking to our website, you must notify us by sending an e-mail to{' '} <a href="mailto:[email protected]" title="send an email to [email protected]" > [email protected] </a> . Please include your name, your organization name, contact information (such as a phone number and/or e-mail address) as well as the URL of your site, a list of any URLs from which you intend to link to our Web site, and a list of the URL(s) on our site to which you would like to link. Allow 2-3 weeks for a response. </p> <p>Approved organizations may hyperlink to our Web site as follows:</p> <ol> <li>By use of our corporate name; or</li> <li> By use of the uniform resource locator (Web address) being linked to; or </li> <li> By use of any other description of our Web site or material being linked to that makes sense within the context and format of content on the linking party's site. </li> </ol> <p> No use of Final Round Esports's logo or other artwork will be allowed for linking absent a trademark license agreement. </p> <h2>Iframes</h2> <p> Without prior approval and express written permission, you may not create frames around our Web pages or use other techniques that alter in any way the visual presentation or appearance of our Web site. </p> <h2>Reservation of Rights</h2> <p> We reserve the right at any time and in its sole discretion to request that you remove all links or any particular link to our Web site. You agree to immediately remove all links to our Web site upon such request. We also reserve the right to amend these terms and conditions and its linking policy at any time. By continuing to link to our Web site, you agree to be bound to and abide by these linking terms and conditions. </p> <h2>Removal of links from our website</h2> <p> If you find any link on our Web site or any linked web site objectionable for any reason, you may contact us about this. We will consider requests to remove links but will have no obligation to do so or to respond directly to you. </p> <p> Whilst we endeavour to ensure that the information on this website is correct, we do not warrant its completeness or accuracy; nor do we commit to ensuring that the website remains available or that the material on the website is kept up to date. </p> <h2>Content Liability</h2> <p> We shall have no responsibility or liability for any content appearing on your Web site. You agree to indemnify and defend us against all claims arising out of or based upon your Website. No link(s) may appear on any page on your Web site or within any context containing content or materials that may be interpreted as libelous, obscene or criminal, or which infringes, otherwise violates, or advocates the infringement or other violation of, any third party rights. </p> <h2>Disclaimer</h2> <p> To the maximum extent permitted by applicable law, we exclude all representations, warranties and conditions relating to our website and the use of this website (including, without limitation, any warranties implied by law in respect of satisfactory quality, fitness for purpose and/or the use of reasonable care and skill). Nothing in this disclaimer will: </p> <ol> <li> limit or exclude our or your liability for death or personal injury resulting from negligence; </li> <li> limit or exclude our or your liability for fraud or fraudulent misrepresentation; </li> <li> limit any of our or your liabilities in any way that is not permitted under applicable law; or </li> <li> exclude any of our or your liabilities that may not be excluded under applicable law. </li> </ol> <p> The limitations and exclusions of liability set out in this Section and elsewhere in this disclaimer: (a) are subject to the preceding paragraph; and (b) govern all liabilities arising under the disclaimer or in relation to the subject matter of this disclaimer, including liabilities arising in contract, in tort (including negligence) and for breach of statutory duty. </p> <p> To the extent that the website and the information and services on the website are provided free of charge, we will not be liable for any loss or damage of any nature. </p> <h2>Credit & Contact Information</h2> <p> This Terms and conditions page was created at{' '} <a style={{ color: 'inherit', textDecoration: 'none', cursor: 'text' }} href="https://termsandconditionstemplate.com" > termsandconditionstemplate.com </a>{' '} generator. If you have any queries regarding any of our terms, please contact us. </p> </PageContent> </Page> ); };
src/modules/Transition/utils/wrapChild.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Transition from '../Transition' /** * Wraps a React element with a Transition component. * * @param {React.ReactElement} child * @param {Function} onHide * @param {Object} [options={}] * @param {String} [options.animation] * @param {Number} [options.duration] * @param {Boolean} [options.directional] * @param {Boolean} [options.transitionOnMount=false] * @param {Boolean} [options.visible=true] */ export default function wrapChild(child, onHide, options = {}) { const { key } = child const { animation, directional, duration, transitionOnMount = false, visible = true } = options return ( <Transition animation={animation} directional={directional} duration={duration} key={key} onHide={onHide} reactKey={key} transitionOnMount={transitionOnMount} visible={visible} > {child} </Transition> ) }
src/components/Root.js
jhegedus42/egghead-redux-playaround
// @flow import {TodoApp} from './TodoApp' import React from 'react'; import {Provider} from 'react-redux'; import type {StoreType } from '../configureStore.js'; import {Router, Route} from 'react-router'; import { browserHistory } from 'react-router' const Root = ({store}:{store:StoreType})=> ( <Provider store = {store}> <Router history={browserHistory}> <Route path='/(:filter)' component ={TodoApp}/> </Router> </Provider> ); export default Root;
src/routes/home/Home.js
ImanMh/react-proto
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Home.css'; class Home extends React.Component { static propTypes = { news: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string.isRequired, link: PropTypes.string.isRequired, content: PropTypes.string, })).isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>React.js News</h1> {this.props.news.map(item => ( <article key={item.link} className={s.newsItem}> <h1 className={s.newsTitle}><a href={item.link}>{item.title}</a></h1> <div className={s.newsDesc} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: item.content }} /> </article> ))} </div> </div> ); } } export default withStyles(s)(Home);
example/events.js
uniphil/react-leaflet
import React, { Component } from 'react'; import { Map, TileLayer, Marker, Popup } from 'react-leaflet'; export default class EventsExample extends Component { constructor() { super(); this.state = { hasLocation: false, latlng: { lat: 51.505, lng: -0.09, }, }; } handleClick() { this.refs.map.leafletElement.locate(); } handleLocationFound(e) { this.setState({ hasLocation: true, latlng: e.latlng, }); } render() { const marker = this.state.hasLocation ? <Marker position={this.state.latlng}> <Popup> <span>You are here</span> </Popup> </Marker> : null; return ( <Map center={this.state.latlng} length={4} onClick={::this.handleClick} onLocationfound={::this.handleLocationFound} ref='map' zoom={13}> <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> {marker} </Map> ); } }
src/layouts/CoreLayout/CoreLayout.js
Grobim/poke-drive
import React from 'react'; import HeaderContainer from 'containers/Header'; import classes from './CoreLayout.scss'; import 'styles/core.scss'; export const CoreLayout = ({ children }) => ( <div className={classes.mainContainer}> <HeaderContainer /> <div className={classes.container}> {children} </div> </div> ); CoreLayout.propTypes = { children: React.PropTypes.element.isRequired }; export default CoreLayout;
src/svg-icons/action/lock-open.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLockOpen = (props) => ( <SvgIcon {...props}> <path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z"/> </SvgIcon> ); ActionLockOpen = pure(ActionLockOpen); ActionLockOpen.displayName = 'ActionLockOpen'; ActionLockOpen.muiName = 'SvgIcon'; export default ActionLockOpen;
src/app/js/MathRow.js
skratchdot/colorify
import React, { Component } from 'react'; import { Row, Col } from 'react-bootstrap'; import MathCol from './MathCol'; class MathRow extends Component { render() { const $this = this; let on = []; let off = []; this.props.flags.forEach(function (val, index) { if (val) { on.push($this.props.type.substr(index, 1)); } else { off.push($this.props.type.substr(index, 1)); } }); on = on.join(','); off = off.join(','); return ( <Row> <Col md={4} sm={6}> <h3 className="type-label"> {this.props.labels.map(function (label, i) { return ( <span key={i} className={$this.props.flags[i] ? 'on' : 'off'}> {label} </span> ); })} </h3> </Col> <Col md={8} sm={6}> <Row> {this.props.cols.map(function (col, i) { return ( <MathCol key={col.fnName + i} type={$this.props.type} flags={$this.props.flags} on={on} off={off} fnName={col.fnName} hex={col.hex} /> ); })} </Row> </Col> </Row> ); } } MathRow.defaultProps = { type: 'RGB', flags: [1, 1, 1], labels: ['R', 'G', 'B'], cols: [], }; export default MathRow;
fields/types/number/NumberColumn.js
rafmsou/keystone
import React from 'react'; import numeral from 'numeral'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var NumberColumn = React.createClass({ displayName: 'NumberColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || isNaN(value)) return null; const formattedValue = (this.props.col.path === 'money') ? numeral(value).format('$0,0.00') : value; return formattedValue; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = NumberColumn;
src/atoms/FlashMessage/index.js
policygenius/athenaeum
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import styles from './flash_message.module.scss'; function FlashMessage(props) { const { children, variant, } = props; return ( <div className={classnames(styles['flash-message'], styles[variant])}> { children } </div> ); } FlashMessage.propTypes = { children: PropTypes.node.isRequired, /** * Possible `variant` animations are: `fadeInDown`, `fadeIn`, `slideDown` */ variant: PropTypes.string }; FlashMessage.propTypes = { children: PropTypes.node.isRequired, variant: PropTypes.string }; FlashMessage.defaultProps = { variant: 'fadeInDown', }; export default FlashMessage;
examples/js/manipulation/strict-search-table.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; const fruits = [ 'banana', 'apple', 'orange', 'tomato', 'strawberries' ]; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Fruit name is ' + fruits[i], price: 2100 + i }); } } addProducts(5); function afterSearch(searchText, result) { console.log('Your search text is ' + searchText); console.log('Result is:'); for (let i = 0; i < result.length; i++) { console.log('Fruit: ' + result[i].id + ', ' + result[i].name + ', ' + result[i].price); } } const options = { afterSearch: afterSearch // define a after search hook }; export default class StrictSearchTable extends React.Component { render() { return ( <BootstrapTable data={ products } search={ true } options={ options }> <TableHeaderColumn dataField='id' isKey={ true } searchable={ false }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Fruit Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
client/src/components/Listing/FullListing.js
Velocies/raptor-ads
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import Carousel from 'nuka-carousel'; import moment from 'moment'; import { Container, Grid, Image, Header, Divider, Message, List, Loader, Button, Modal, Form, Card } from 'semantic-ui-react'; import GoogleMapContainer from '../GoogleMap/GoogleMapContainer'; import { getCurrentListing, changeContactField, sendMessage } from '../../actions/fullListingActions'; import { clearErrors, removeListing } from '../../actions/listingActions'; import RatingCard from '../Ratings/RatingCard'; import ListingDeleteModal from '../shared/ListingDeleteModal'; import ReplyFormModal from '../Profile/Inbox/ReplyFormModal'; class FullListing extends Component { constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentWillMount() { this.props.dispatch(getCurrentListing(this.props.listingId)); } onSubmit(e) { e.preventDefault(); const data = this.props.contactForm; const postId = this.props.listingId; const senderId = this.props.loggedInUser.id; const userId = this.props.currentListing.user.id; const payload = { title: data.title, body: data.body, postId, userId, senderId }; this.props.dispatch(clearErrors()); this.props.dispatch(sendMessage(payload)); } onChange(e, data) { if (data) { this.props.dispatch(changeContactField('type', data.value)); } else { this.props.dispatch(changeContactField(e.target.name, e.target.value)); } } convertTime(time) { return moment(time).fromNow(); } renderRecentRatings(ratings) { if (!ratings) { return []; } return ratings .slice(0, 3) .map(r => <RatingCard stars={r.stars} editable={false} content={r.content} rater={r.rater} />); } handleDelete() { const { listingId } = this.props; const { id: userId } = this.props.loggedInUser; this.props.dispatch(removeListing(listingId, userId)); } render() { const { loggedInUser, isFetching, currentListing, userListings, dispatch } = this.props; if (isFetching) { return <Loader active inline="centered" />; } const currentListingArray = [currentListing]; return ( <Container textAlign="center"> <Header as="h1" className="center">-- {currentListing.title || 'Current Listing'} -- <br /></Header> <Header as="h4" className="center" color="grey">{`Created ${this.convertTime(currentListing.createdAt)}` || 'Time Created'}</Header> { loggedInUser.id === currentListing.userId ? <ListingDeleteModal handleDelete={this.handleDelete} /> : null } <Divider /> <Message color="grey"> <Grid columns={2} textAlign="left"> <Grid.Column> <Header as="h2" className="center">Job Description</Header> <Grid.Row> <p>{currentListing.body}</p> </Grid.Row> <Grid.Row verticalAlign="bottom"> <Divider hidden section /> <Carousel> { currentListing.pictures.map(p => <Image key={p.id} src={p.img_path} />) } </Carousel> </Grid.Row> </Grid.Column> <Grid.Column> <Grid.Row> <GoogleMapContainer markers={currentListingArray} /> </Grid.Row> <Divider hidden /> <Grid.Row columns={2}> <Grid.Column> <List> <List.Item> <List.Icon name="users" /> <List.Content> <Link to={`/user/${currentListing.user.id}`}> {`${currentListing.user.firstName} ${currentListing.user.lastName}` || 'Customer Name'} </Link> </List.Content> </List.Item> <List.Item> <List.Icon name="marker" /> <List.Content>{`${currentListing.city}, ${currentListing.state}`}</List.Content> </List.Item> <List.Item> <List.Icon name="mail" /> <List.Content> {`${currentListing.user.email}`} </List.Content> </List.Item> </List> </Grid.Column> <Divider hidden /> <Grid.Column> <ReplyFormModal onChange={this.onChange} onSubmit={this.onSubmit} listingId={currentListing.id} userId={loggedInUser.id} /> </Grid.Column> </Grid.Row> </Grid.Column> </Grid> <Divider clearing /> <Divider hidden /> <Grid centered> <Grid.Row> <Header as="h3"> {`Recent Ratings for ${currentListing.user.firstName}`} </Header> </Grid.Row> { currentListing.user.ratings && !currentListing.user.ratings.length ? <span>No Ratings for { currentListing.user.firstName }</span> : <Grid> <Grid.Row centered> <Card.Group> { this.renderRecentRatings(currentListing.user.ratings) } </Card.Group> </Grid.Row> <Grid.Row> <Link to={`/user/${currentListing.user.id}/ratings`}> View All </Link> </Grid.Row> </Grid> } </Grid> </Message> </Container> ); } } const mapStateToProps = (state) => { const { currentListing, userListings, isFetching } = state.listing; const { contactForm } = state.messages; const { user } = state.listing.currentListing; const { loggedInUser } = state.auth; const { pathname } = state.routing.locationBeforeTransitions; const listingId = pathname.split('/')[2]; return { loggedInUser, currentListing, contactForm, userListings, isFetching, listingId, user, }; }; FullListing.propTypes = { isFetching: React.PropTypes.bool.isRequired, dispatch: React.PropTypes.func.isRequired, }; export default connect(mapStateToProps)(FullListing);
step7-unittest/app/js/components/Profile.js
jintoppy/react-training
import React from 'react'; const Profile = (props) => { return ( < div > Profile Page { props.name } < /div>); } export default Profile;
src/components/Common/Navbar.js
MattMcFarland/tw-client
import React, { Component } from 'react'; import UserActions from '../../actions/UserActions'; import UserStore from '../../stores/UserStore'; import connectStores from 'alt/utils/connectToStores'; import DropDown from './DropDown'; class Navbar extends Component { constructor(props) { super(props); this.state = UserStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { //console.log(this.handlers); UserStore.listen(this.onChange); UserActions.init(); } componentWillUnmount() { UserStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } loremOption() { console.log('loremOption clicked'); } ipsumOption() { console.log('ipsum clicked'); } render () { return ( <header> <nav className="topbar"> <div className="topbar__content"> <div className="row"> <div className="col-lg-9 col-lg-offset-2"> <a href="/" className="topbar__logo">WT</a> <ul className="topbar__list pull-right"> <li className="topbar__list__item"> {this.state && this.state.username ? <DropDown title="Account" options={[ { type: "link", href: "/account", icon: "user", title: "My Account" }, { type: "link", href: "/logout", icon: "log-out", title: "Logout" } ]} /> : <a href="/login">Login</a> } </li> </ul> </div> </div> </div> </nav> </header> ); } } export default Navbar;
app/javascript/flavours/glitch/features/lists/index.js
vahnj/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from 'flavours/glitch/components/loading_indicator'; import Column from 'flavours/glitch/features/ui/components/column'; import ColumnBackButtonSlim from 'flavours/glitch/components/column_back_button_slim'; import { fetchLists } from 'flavours/glitch/actions/lists'; 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 NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; const messages = defineMessages({ heading: { id: 'column.lists', defaultMessage: 'Lists' }, subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' }, }); const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ lists: getOrderedLists(state), }); @connect(mapStateToProps) @injectIntl export default class Lists extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, lists: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchLists()); } render () { const { intl, lists } = this.props; if (!lists) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='bars' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <div className='scrollable'> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> {lists.map(list => <ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='list-ul' text={list.get('title')} /> )} </div> </Column> ); } }
app/containers/NotFoundPage/index.js
j921216063/chenya
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; export default function NotFound() { return ( <article> <H1> <FormattedMessage {...messages.header} /> </H1> </article> ); }
src/application-box.js
slx-dev/react-testing
import React from 'react'; import ApplicationList from './application-list'; import Jumbotron from './jumbotron'; import PRODUCTS from './products.json'; export default class ApplicationBox extends React.Component { constructor(props) { super(props); this.state = { data: PRODUCTS }; } // loadApplicationsFromServer() { // $.ajax({ // url: '/api/apps', // dataType: 'json', // cache: false, // success: function(data) { // this.setState({ // data: [] // }); // }.bind(this), // error: function(xhr, status, err) { // console.error(this.props.url, status, err.toString()); // }.bind(this) // }); // } // handleApplicationSubmit(application) { // var applications = this.state.data; // Optimistically set an id on the new application. It will be replaced by an // id generated by the server. In a applicationion application you would likely // not use Date.now() for this and would have a more robust system in place. // application.id = Date.now(); // var newApplications = applications.concat([application]); // this.setState({ data: newApplications }); // $.ajax({ // url: '/api/apps', // dataType: 'json', // type: 'POST', // data: application, // success: function(data) { // this.setState({ data: data }); // }.bind(this), // error: function(xhr, status, err) { // this.setState({ data: applications }); // console.error(this.props.url, status, err.toString()); // }.bind(this) // } // ); // }, // componentDidMount() { // this.loadApplicationsFromServer(); // setInterval(this.loadApplicationsFromServer, 2000); // } render() { return ( <div className="applicationBox"> <Jumbotron/> <ApplicationList data={this.state.data} /> </div>); } } // <ApplicationForm onApplicationSubmit={this.handleApplicationSubmit} />
benchmarks/dom-comparison/src/implementations/react-fela-useFela/Box.js
risetechnologies/fela
import React from 'react' import { useFela } from 'react-fela' const rule = ({ color, fixed = false, layout = 'column', outer = false }) => ({ alignItems: 'stretch', borderWidth: '0px', borderStyle: 'solid', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: '0', margin: '0px', padding: '0px', position: 'relative', // fix flexbox bugs minHeight: '0px', minWidth: '0px', ...styles[`color${color}`], ...(fixed && styles.fixed), ...(layout === 'row' && styles.row), ...(outer && styles.outer), }) const Box = ({ children, color, fixed, layout, outer }) => { const { css } = useFela({ color, fixed, layout, outer }) return <div className={css(rule)}>{children}</div> } const styles = { outer: { alignSelf: 'flex-start', padding: '4px', }, row: { flexDirection: 'row', }, color0: { backgroundColor: '#14171A', }, color1: { backgroundColor: '#AAB8C2', }, color2: { backgroundColor: '#E6ECF0', }, color3: { backgroundColor: '#FFAD1F', }, color4: { backgroundColor: '#F45D22', }, color5: { backgroundColor: '#E0245E', }, fixed: { width: '6px', height: '6px', }, } export default Box
src/svg-icons/action/group-work.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGroupWork = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5zM9.5 8c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8zm6.5 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); ActionGroupWork = pure(ActionGroupWork); ActionGroupWork.displayName = 'ActionGroupWork'; ActionGroupWork.muiName = 'SvgIcon'; export default ActionGroupWork;
classic/src/scenes/mailboxes/src/Components/Backed/MailboxAvatar.js
wavebox/waveboxapp
import React from 'react' import PropTypes from 'prop-types' import { accountStore } from 'stores/account' import shallowCompare from 'react-addons-shallow-compare' import Resolver from 'Runtime/Resolver' import ACAvatarCircle2 from 'wbui/ACAvatarCircle2' export default class MailboxAvatar extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { mailboxId: PropTypes.string.isRequired } /* **************************************************************************/ // Component Lifecycle /* **************************************************************************/ componentDidMount () { accountStore.listen(this.accountChanged) } componentWillUnmount () { accountStore.unlisten(this.accountChanged) } componentWillReceiveProps (nextProps) { if (this.props.mailboxId !== nextProps.mailboxId) { this.setState({ avatar: accountStore.getState().getMailboxAvatarConfig(nextProps.mailboxId) }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { return { avatar: accountStore.getState().getMailboxAvatarConfig(this.props.mailboxId) } })() accountChanged = (accountState) => { this.setState({ avatar: accountState.getMailboxAvatarConfig(this.props.mailboxId) }) } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { mailboxId, ...passProps } = this.props const { avatar } = this.state return ( <ACAvatarCircle2 avatar={avatar} resolver={(i) => Resolver.image(i)} {...passProps} /> ) } }
es/components/style/cancel-button.js
dearkaran/react-planner
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import Button from './button'; var STYLE = { borderColor: "#adadad", backgroundColor: "#e6e6e6" }; var STYLE_HOVER = { backgroundColor: "#d4d4d4", borderColor: "#8c8c8c" }; export default function CancelButton(_ref) { var children = _ref.children, rest = _objectWithoutProperties(_ref, ['children']); return React.createElement( Button, _extends({ style: STYLE, styleHover: STYLE_HOVER }, rest), children ); }
src/components_OLD/Layout.js
travism26/microservice-frontend
import React, { Component } from 'react'; import logo from './../logo.svg'; import '../App.css'; import Footer from "./Footer"; import Header from "./Header"; class Layout extends Component { render() { const title = "Welcome Travis!"; return ( <div className="App"> <h1>hello world</h1> </div> ); } } export default Layout;
MadWare.Hathor.FrontEnd/src/js/components/client/Client.js
zvizdo/MadWare.Hathor
import React from 'react' import { connect } from 'react-redux' import AddToPlaylist from './../shared/AddToPlaylist'; import CurrentlyPlaying from './../shared/CurrentlyPlaying'; import Playlist from './../shared/Playlist'; import setupActions from './../../actions/setupActions'; import clientActions from './../../actions/clientActions'; import { baseRemoteUrl } from './../../httpConfig'; import SignalRConnection from './../../utils/SignalRConnection'; import { canPlayVideo, getVideoIdx } from './../../utils/playlist'; import { createSignature } from './../../utils/utils'; class Client extends React.Component { constructor(){ super(); this.hub = new SignalRConnection(baseRemoteUrl); this.hub.setReceiveMessageCallback(this.onServerMessageRecieved.bind(this)); } componentWillMount() { this.props.dispatch( setupActions.clearServer() ); this.props.dispatch( setupActions.setServerIdOnClient(this.props.params.serverId) ); this.props.dispatch( setupActions.generateClientId(this.hub, this.props.params.serverId) ); } onVideoInputChange(e){ this.setState( { addedVideoId: e.target.value } ); } onAddVideoToPlaylist(videoId){ let secretId = createSignature( this.props.client.serverId+this.props.client.id, videoId ); this.props.dispatch( clientActions.addVideo(this.props.client.serverId, videoId, secretId) ); } componentWillUnmount() { this.hub.disconnect(); } onServerMessageRecieved(action){ this.props.dispatch(action); switch (action.type) { case "CLIENT_REGISTER_WITH_SERVER": if(action.payload) this.props.dispatch( clientActions.refreshPlaylist(this.props.params.serverId, this.props.client.id) ); break; } } onRemoveVideoPlaylist(videoId) { let action = { type: "PLAYLIST_REMOVE_VIDEO", payload: { videoId: videoId, serverId: this.props.client.serverId, clientId: this.props.client.id } } this.props.dispatch( clientActions.pushToServer( this.props.client.serverId, this.props.client.id, action ) ); } onUpVoteVideoPlaylist(videoId) { let action = { type: "PLAYLIST_UPVOTE_VIDEO", payload: { videoId: videoId, serverId: this.props.client.serverId, clientId: this.props.client.id } } this.props.dispatch( clientActions.pushToServer( this.props.client.serverId, this.props.client.id, action ) ); } getVideoToPlay() { if (!this.props.playlist.currentVideoId) return null; let crntVidIdx = getVideoIdx(this.props.playlist.currentVideoId, this.props.playlist.videos); if( crntVidIdx === null || crntVidIdx >= this.props.playlist.videos.length) return null; return this.props.playlist.videos[crntVidIdx]; } render() { let video = this.getVideoToPlay(); return ( <div> {this.props.client.serverExists ? (<AddToPlaylist onVideoAdded={this.onAddVideoToPlaylist.bind(this)} />) : null} {video ? (<CurrentlyPlaying video={video} />) : null} <Playlist serverId={this.props.client.serverId} clientId={this.props.client.id} serverExists={this.props.client.serverExists} videos={this.props.playlist.videos} currentVideoId={this.props.playlist.currentVideoId} onPlaylistRemoveVideo={this.onRemoveVideoPlaylist.bind(this)} onPlaylistUpVoteVideo={this.onUpVoteVideoPlaylist.bind(this)} /> </div> ); } } function mapStateToProps(state){ return { client: state.client, playlist: state.playlist }; } export default connect(mapStateToProps)(Client);
src/webapp.js
AlhasanIQ/PiTrol
import React, { Component } from 'react'; var plugins = require('./plugins') const componentList = [] for (var i = 0; i < plugins.length; i++) { const plugin = plugins[i] const uiComponent = plugin.ref.uiComponent componentList.push(uiComponent) } export default class WebApp extends Component { render() { return ( <div className="fluid-container"> <div className="row"> {/* confused about the `...e.props` ? read about "es6 spread operator" and "react spread attributes"*/} { componentList.map((e, i) => <div className="col-md-4"><e.ref {...e.props} /></div>) } </div> </div> ); } }
src/components/Footer/Footer.js
expdevelop/d812
import React from 'react' import { Container, Link, Title, FlexGrid, Content, Svg } from 'components' import s from './Footer.sass' import { socialLinks, navMail, navPhones } from 'config' import { CATALOG as catalogLink } from 'constants/urls' import logoIcon from 'icons/logo.svg' const Footer = ({onHelpClick, address, phone}) => ( <footer className={s.footer}> <Container> <FlexGrid wrap="true" justify="space-between" align="stretch"> <div className={s.col}> <Title className={s.title} light white size="3"> <Link to="/about" inherit>О нас</Link> </Title> <Content size="5" transparent white> Интернет-магазин будущего. <br/> Ваш персональный менеджер с <br/> умным поиском и моментальной фильтрацией каталога товаров. </Content> </div> <FlexGrid justify="center" align="start" className={s.col__wide}> <div className={s.links}> <Link to={catalogLink} size="4" className={s.link} white>Каталог товаров</Link> {/* todo: open chat */} <Link to="javascript:;" onClick={onHelpClick} size="4" className={s.link} white>Помощь</Link> <Link to="?account&signup" size="4" className={s.link} white>Регистрация</Link> <Link to="?account&signin" size="4" className={s.link} white>Вход</Link> </div> <div className={s.links}> <Link to="/about" size="4" className={s.link} white>О компании</Link> <Link to="/protect" size="4" className={s.link} white>Гарантии</Link> <Link to="/delivery" size="4" className={s.link} white>Доставка и оплата</Link> <Link to="https://market.yandex.ru/shop/46912/reviews" target="_blank" size="4" className={s.link} white>Отзывы</Link> </div> </FlexGrid> <div className={s.col}> <Title className={s.title} light white size="3"> <Link to="/contact" inherit>Контакты</Link> </Title> <Content nooffsets size="5" transparent white> {address} </Content> <div className={s.info}> <Link to={`mailto:${navMail}`} target="_blank" size="5" transparent white> {navMail} </Link> <br/> <Link to={`tel:${phone}`} target="_blank" size="5" transparent white> {phone} </Link> </div> <div className={s.socials}> {Object.keys(socialLinks).map(item => { const val = socialLinks[item]; return ( <Content href={val.link} target='_blank' size="5" transparent white tag="a" key={item} className={s.socials__link}> {val.name} </Content> ) })} </div> </div> </FlexGrid> <FlexGrid className={s.bottom} wrap="true" justify="space-between" align="stretch"> <div className={s.col}> <FlexGrid justify="start" align="center"> <Content white nooffsets size="5" transparent>© 2017</Content> <Svg src={logoIcon} className={s.logo}/> </FlexGrid> <Content transparent size="6" white>Данный сайт не является публичной офертой.</Content> </div> <div className={s.col}> <Content transparent size="5" nooffsets white>ООО "Союз-Связь Санкт-Петербург"</Content> <Content transparent size="5" nooffsets white>ОГРН: 1137847491495</Content> </div> </FlexGrid> </Container> </footer> ); export default Footer;
app/containers/NotFoundPage/index.js
theseushu/runcai
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/pages/conference/people/staff/edit/rolesActive.js
sunway-official/acm-admin
import React, { Component } from 'react'; import { ListItem, Toggle } from 'material-ui'; import { graphql, compose } from 'react-apollo'; import { connect } from 'react-redux'; import { queries, mutations } from '../helpers'; class RoleItem extends Component { constructor(props) { super(props); this.handleUpdate = this.handleUpdate.bind(this); } async handleUpdate(role) { try { await this.props.UPDATE_USER_ROLE_STATUS({ variables: { user_id: this.props.id, role_id: role.id, status: role.status === 'on' ? 'off' : 'on', conference_id: this.props.conference_id, }, refetchQueries: [ { query: queries.GET_ALL_ROLES_ACTIVE_BY_USER_ID_QUERY, variables: { user_id: this.props.id, conference_id: this.props.conference_id, }, }, ], }); } catch (error) { throw error; } } state = { role: {}, }; render() { const role = this.props.role; const rolesActive = this.props.rolesActive; // const roles = this.props.roles; return ( <ListItem primaryText={role.name} rightToggle={ <Toggle defaultToggled={rolesActive.includes(role.id) ? true : false} onToggle={() => this.handleUpdate(role)} /> } /> ); } } const mapStateToProps = state => { return { id: state.user.data.id, conference_id: state.conference.id, }; }; export default compose( connect(mapStateToProps, undefined), graphql(mutations.UPDATE_USER_ROLE_STATUS, { name: 'UPDATE_USER_ROLE_STATUS', }), )(RoleItem);
src/px-alert-label/index.js
jonniespratley/px-components-react
import React from 'react'; import classnames from 'classnames'; import style from './style.scss'; import BaseComponent from '../base-component'; /** * px-alert-label component */ export default ({label, type = 'info', badge, children}) => { const _isCircle = (t) =>{ return t === 'unknown'; }; const _getPoints = (t) => { if(t === 'important') { return '16.5,3 32,30 1,30'; } else if(t === 'warning') { return '16,0.5 32.5,16 16,32.5, 0.5,16'; } else if(t === 'info' || t === 'information') { return '6.6,32.5 26.4,32.5 32.5,13 16,0.5 0.5,13'; } else { return '3,3 3,30 30,30 30,3'; } }; const classNames = classnames('alertlabel', type, badge); return ( <div className='px-alert-label'> <span className={classNames}> {badge && <div> {!_isCircle(type) && <svg className="svg-canvas" viewBox="0 0 33 33"> <polygon id="polygon" points={_getPoints(type)}/> </svg> } {_isCircle(type) && <svg className="svg-canvas" viewBox="0 0 33 33"> <circle id="circle" cx="16" cy="16" r="15"/> </svg> } </div>} <div className='label'> <span className='label__text'>{label}</span> </div> </span> <style jsx>{style}</style> </div> ); };
src/components/ui/button/full_button.js
KmKm007/oa
import React from 'react' import PropTypes from 'prop-types' import BaseButton from './base_button' class FullButton extends React.Component { static propTypes = { className: PropTypes.string } render () { let { className, ...restProps } = this.props className = className || 'full-button' return ( <BaseButton className={className} {...restProps} /> ) } } export default FullButton
src/client/components/FilterView/DeleteDeviceLink.js
ZeusTheTrueGod/background-geolocation-console
// @flow import React from 'react'; import Link from 'react-toolbox/lib/link'; import { connect } from 'react-redux'; import { type GlobalState } from '~/reducer/state'; import { deleteActiveDevice } from '~/reducer/dashboard'; type StateProps = {| isVisible: boolean, |}; type DispatchProps = {| onClick: () => any, |}; type Props = {| ...StateProps, ...DispatchProps |}; const DeleteDeviceLink = ({ isVisible, onClick }: Props) => { if (!isVisible) { return null; } return ( <Link style={{ position: 'relative', top: -72, right: -60, colord: 'red', }} href='#' onClick={(e: Event) => { e.preventDefault(); if (confirm('Delete device and all its locations?')) { onClick(); } }} label='Delete' active /> ); }; const mapStateToProps = function (state: GlobalState): StateProps { return { isVisible: state.dashboard.devices.length > 0, }; }; const mapDispatchToProps: DispatchProps = { onClick: deleteActiveDevice, }; export default connect(mapStateToProps, mapDispatchToProps)(DeleteDeviceLink);
src/components/LandingFooter/LandingFooter.js
Anshul-HL/blitz-windermere
import React, { Component } from 'react'; import { Row, Col, Grid } from 'react-bootstrap'; export default class LandingFooter extends Component { render() { const styles = require('./LandingFooter.scss'); return ( <Grid fluid className={styles.footer}> <Row className={styles.footerWrapper}> <Col xs={6}> <p>Homevista Decor & Furnishing Pvt. Ltd. © 2016</p> </Col> <Col xs={6}> <p className={styles.follow_us}>Follow us on <a href="https://www.facebook.com/homelaneinteriors" target="_blank" className={styles.blue}> <strong> facebook</strong> </a> </p> </Col> </Row> </Grid> ); } }
examples/js/selection/selection-column-width-table.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); const selectRowProp = { mode: 'checkbox', columnWidth: '60px' }; export default class SelectionColumnWidthTable extends React.Component { render() { return ( <BootstrapTable data={ products } selectRow={ selectRowProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/components/travis/plain-wordmark/TravisPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './TravisPlainWordmark.svg' /** TravisPlainWordmark */ function TravisPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'TravisPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } TravisPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default TravisPlainWordmark
src/components/Navigation/Navigation.js
fkn/ndo
import PropTypes from 'prop-types'; import React from 'react'; import { Nav, Navbar, NavItem } from 'react-bootstrap'; import { connect } from 'react-redux'; import Link from '../Link'; function logout(event) { event.preventDefault(); fetch('/logout', { method: 'POST' }).then( () => (window.location.pathname = 'login'), ); } const Navigation = ({ user }) => ( <Navbar inverse fixedTop defaultExpanded fluid> <Navbar.Header> <Navbar.Brand> <Link to="/">NDO</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavItem componentClass={Link} eventKey={1} to="/courses" href="/courses" > Courses </NavItem> {user && user.isAdmin && ( <NavItem componentClass={Link} eventKey={2} to="/users" href="/users" > Users </NavItem> )} {user && ( <NavItem componentClass={Link} eventKey={3} to="/files" href="/files"> Files </NavItem> )} {user && user.isAdmin && ( <NavItem componentClass={Link} eventKey={4} to="/tests" href="/tests" > Tests </NavItem> )} {user && user.isAdmin && ( <NavItem componentClass={Link} eventKey={5} to="/codejudge" href="/codejudge" > Codejudge </NavItem> )} </Nav> {user ? ( <Nav pullRight> <NavItem componentClass={Link} eventKey={1} to={`/users/${user.id}`} href={`/users/${user.id}`} > {user.email} </NavItem> <NavItem eventKey={2} onClick={logout}> Log out </NavItem> </Nav> ) : ( <Nav pullRight> <NavItem componentClass={Link} eventKey={1} to="/login" href="/login"> Log in </NavItem> {/* <NavItem componentClass={Link} eventKey={2} to="/register" href="/register" > Sign up </NavItem> */} </Nav> )} </Navbar.Collapse> </Navbar> ); Navigation.propTypes = { user: PropTypes.shape({ id: PropTypes.string.isRequired, email: PropTypes.string.isRequired, }), }; Navigation.defaultProps = { user: null, }; export default connect(state => ({ user: state.user, }))(Navigation);
node_modules/[email protected]@antd/es/breadcrumb/Breadcrumb.js
ligangwolai/blog
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import { cloneElement } from 'react'; import warning from '../_util/warning'; import BreadcrumbItem from './BreadcrumbItem'; import classNames from 'classnames'; function getBreadcrumbName(route, params) { if (!route.breadcrumbName) { return null; } var paramsKeys = Object.keys(params).join('|'); var name = route.breadcrumbName.replace(new RegExp(':(' + paramsKeys + ')', 'g'), function (replacement, key) { return params[key] || replacement; }); return name; } function defaultItemRender(route, params, routes, paths) { var isLastItem = routes.indexOf(route) === routes.length - 1; var name = getBreadcrumbName(route, params); return isLastItem ? React.createElement( 'span', null, name ) : React.createElement( 'a', { href: '#/' + paths.join('/') }, name ); } var Breadcrumb = function (_React$Component) { _inherits(Breadcrumb, _React$Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, (Breadcrumb.__proto__ || Object.getPrototypeOf(Breadcrumb)).apply(this, arguments)); } _createClass(Breadcrumb, [{ key: 'componentDidMount', value: function componentDidMount() { var props = this.props; warning(!('linkRender' in props || 'nameRender' in props), '`linkRender` and `nameRender` are removed, please use `itemRender` instead, ' + 'see: https://u.ant.design/item-render.'); } }, { key: 'render', value: function render() { var crumbs = void 0; var _props = this.props, separator = _props.separator, prefixCls = _props.prefixCls, style = _props.style, className = _props.className, routes = _props.routes, _props$params = _props.params, params = _props$params === undefined ? {} : _props$params, children = _props.children, _props$itemRender = _props.itemRender, itemRender = _props$itemRender === undefined ? defaultItemRender : _props$itemRender; if (routes && routes.length > 0) { var paths = []; crumbs = routes.map(function (route) { route.path = route.path || ''; var path = route.path.replace(/^\//, ''); Object.keys(params).forEach(function (key) { path = path.replace(':' + key, params[key]); }); if (path) { paths.push(path); } return React.createElement( BreadcrumbItem, { separator: separator, key: route.breadcrumbName || path }, itemRender(route, params, routes, paths) ); }); } else if (children) { crumbs = React.Children.map(children, function (element, index) { if (!element) { return element; } warning(element.type && element.type.__ANT_BREADCRUMB_ITEM, 'Breadcrumb only accepts Breadcrumb.Item as it\'s children'); return cloneElement(element, { separator: separator, key: index }); }); } return React.createElement( 'div', { className: classNames(className, prefixCls), style: style }, crumbs ); } }]); return Breadcrumb; }(React.Component); export default Breadcrumb; Breadcrumb.defaultProps = { prefixCls: 'ant-breadcrumb', separator: '/' }; Breadcrumb.propTypes = { prefixCls: PropTypes.string, separator: PropTypes.node, routes: PropTypes.array, params: PropTypes.object, linkRender: PropTypes.func, nameRender: PropTypes.func };
sources/components/about.js
markuswustenberg/template
import React from 'react' export default class About extends React.Component { render() { return ( <div> <h1>😎 template</h1> <p>Find the source code on <a href="https://github.com/markuswustenberg/template">Github</a>.</p> </div> ) } }
react-flux-mui/js/material-ui/src/svg-icons/av/playlist-add.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPlaylistAdd = (props) => ( <SvgIcon {...props}> <path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zm4 8v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zM2 16h8v-2H2v2z"/> </SvgIcon> ); AvPlaylistAdd = pure(AvPlaylistAdd); AvPlaylistAdd.displayName = 'AvPlaylistAdd'; AvPlaylistAdd.muiName = 'SvgIcon'; export default AvPlaylistAdd;
app/components/Tabs/Tab.js
lgarcin/LatexElectronReact
import React, { Component } from 'react'; import styles from './Tab.css'; export default class Tab extends Component { render() { const activeClass = this.props.active ? styles.active : ''; return ( <li className={`${styles.tab} ${activeClass}`}> <a role="button" tabIndex="0" onClick={() => this.props.changeTab()}> {this.props.label} </a> <a role="button" tabIndex="0" className={styles.cross} onClick={() => this.props.removeTab()}> <span> &#x2716; </span> </a> </li> ); } } Tab.propTypes = { label: React.PropTypes.string.isRequired, active: React.PropTypes.bool.isRequired, changeTab: React.PropTypes.func.isRequired, removeTab: React.PropTypes.func.isRequired };
src/js/components/Flurries.js
Fraina/React-Weather-Widget
import React, { Component } from 'react'; export default class Flurries extends Component { render() { return ( <div className="icon"> <div className="cloud"></div> <div className="snow"> <div className="flake"></div> <div className="flake"></div> </div> </div> ); } }
src/svg-icons/image/leak-remove.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLeakRemove = (props) => ( <SvgIcon {...props}> <path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z"/> </SvgIcon> ); ImageLeakRemove = pure(ImageLeakRemove); ImageLeakRemove.displayName = 'ImageLeakRemove'; ImageLeakRemove.muiName = 'SvgIcon'; export default ImageLeakRemove;
src/Icon.js
jareth/react-materialize
import React from 'react'; import constants from './constants'; import cx from 'classnames'; class Icon extends React.Component { render() { let classes = { 'material-icons': true }; constants.PLACEMENTS.forEach(p => { classes[p] = this.props[p]; }); constants.ICON_SIZES.forEach(s => { classes[s] = this.props[s]; }); return <i className={cx(classes, this.props.className)}>{this.props.children}</i>; } } Icon.propTypes = { tiny: React.PropTypes.bool, small: React.PropTypes.bool, medium: React.PropTypes.bool, large: React.PropTypes.bool }; export default Icon;
src/modules/todo/components/TodoInlineForm.js
scubism/react_todo_web
import React from 'react' import autobind from 'autobind-decorator' import { reduxForm } from 'redux-form' import { createTodo, updateTodo, focusTodo } from '../actions' const fields = [ 'id', 'title', 'due_date', 'color', 'marked', ] @autobind class _TodoInlineForm extends React.Component { componentDidMount() { this.refs.titleInput.focus(); } _handleSubmit(values) { return new Promise((resolve, reject) => { if (!values.title) { reject({title: 'Please input a title.', _error: "Submit validation failed."}); return; } this.props.dispatch(this._submitAction( values, resolve, (e) => { alert(e); reject();})); }); } render() { const { fields: {id, title, due_date, color, marked}, handleSubmit, submitting } = this.props return( <form className="todo-inline-form" onSubmit={handleSubmit(values => this._handleSubmit(values))} onBlur={this._onBlur} > <div> <input ref="titleInput" className={"new-todo" + (title.error ? " error" : "")} placeholder={title.error || "What needs to be done?"} disabled={submitting} {...title} /> </div> </form> ) } } @reduxForm({ form: 'TodoInlineCreateForm', fields }) export class TodoInlineCreateForm extends _TodoInlineForm { _submitAction(values, resolve, reject) { const { resetForm } = this.props; const titleInput = this.refs.titleInput; return createTodo({ data: values, resolve: () => { resetForm(); titleInput.focus(); resolve(); }, reject }); } _onBlur() {} } @reduxForm({ form: 'TodoInlineUpdateForm', fields }) @autobind export class TodoInlineUpdateForm extends _TodoInlineForm { _submitAction(values, resolve, reject) { const { resetForm, dispatch } = this.props; return updateTodo({ id: values.id, data: values, resolve: () => { resetForm(); dispatch(focusTodo(null)); resolve(); }, reject }); } _onBlur() { const { dispatch } = this.props; dispatch(focusTodo(null)); } }
docs/client/components/pages/Linkify/index.js
draft-js-plugins/draft-js-plugins-v1
import React, { Component } from 'react'; import Container from '../../shared/Container'; import AlternateContainer from '../../shared/AlternateContainer'; import Heading from '../../shared/Heading'; import styles from './styles.css'; import Code from '../../shared/Code'; import SimpleLinkifyEditor from './SimpleLinkifyEditor'; import CustomLinkifyEditor from './CustomLinkifyEditor'; import simpleExampleCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleLinkifyEditor'; import simpleExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./SimpleLinkifyEditor/editorStyles.css'; import customExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomLinkifyEditor'; import customExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomLinkifyEditor/editorStyles.css'; import gettingStarted from '!!../../../loaders/prism-loader?language=javascript!./gettingStarted'; import SocialBar from '../../shared/SocialBar'; import NavBar from '../../shared/NavBar'; import Separator from '../../shared/Separator'; import webpackConfig from '!!../../../loaders/prism-loader?language=javascript!./webpackConfig'; import webpackImport from '!!../../../loaders/prism-loader?language=javascript!./webpackImport'; import ExternalLink from '../../shared/Link'; import InlineCode from '../../shared/InlineCode'; export default class App extends Component { render() { return ( <div> <NavBar /> <Separator /> <Container> <Heading level={ 2 }>Linkify</Heading> </Container> <AlternateContainer> <Heading level={ 2 }>Getting Started</Heading> <Code code="npm install draft-js-plugins-editor --save" /> <Code code="npm install draft-js-linkify-plugin --save" /> <Code code={ gettingStarted } name="gettingStarted.js" /> <Heading level={ 3 }>Importing the default styles</Heading> <p> The plugin ships with a default styling available at this location in the installed package: &nbsp; <InlineCode code={ 'node_modules/draft-js-linkify-plugin/lib/plugin.css' } /> </p> <Heading level={ 4 }>Webpack Usage</Heading> <ul className={ styles.list }> <li className={ styles.listEntry }> 1. Install Webpack loaders: &nbsp; <InlineCode code={ 'npm i style-loader css-loader --save-dev' } /> </li> <li className={ styles.listEntry }> 2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list. <Code code={ webpackConfig } className={ styles.guideCodeBlock } /> </li> <li className={ styles.listEntry }> 3. Add the below import line to your component to tell Webpack to inject the style to your component. <Code code={ webpackImport } className={ styles.guideCodeBlock } /> </li> <li className={ styles.listEntry }> 4. Restart Webpack. </li> </ul> <Heading level={ 4 }>Browserify Usage</Heading> <p> Please help, by submiting a Pull Request to the <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Linkify/index.js">documentation</ExternalLink>. </p> </AlternateContainer> <Container> <Heading level={ 2 }>Configuration Parameters</Heading> <div className={ styles.param }> <span className={ styles.paramName }>theme</span> <span>Object of CSS classes with the following keys.</span> <div className={ styles.subParams }> <div className={ styles.subParam }><span className={ styles.subParamName }>link:</span> CSS class to be applied to link text</div> </div> </div> <div className={ styles.param }> <span className={ styles.paramName }>target</span> <span>String value for the target attribute. (Default value is _self)</span> </div> </Container> <Container> <Heading level={ 2 }>Simple Example</Heading> <SimpleLinkifyEditor /> <Code code={ simpleExampleCode } name="SimpleLinkifyEditor.js" /> <Code code={ simpleExampleEditorStylesCode } name="editorStyles.css" /> </Container> <Container> <Heading level={ 2 }>Themed Linkify Example</Heading> <CustomLinkifyEditor /> <Code code={ customExampleCode } name="CustomLinkifyEditor.js" /> <Code code={ customExampleEditorStylesCode } name="editorStyles.css" /> </Container> <SocialBar /> </div> ); } }
es/components/Chat/Markup/StrikeThrough.js
welovekpop/uwave-web-welovekpop.club
import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; var StrikeThrough = function StrikeThrough(_ref) { var children = _ref.children, props = _objectWithoutProperties(_ref, ["children"]); return React.createElement("s", props, children); }; StrikeThrough.propTypes = process.env.NODE_ENV !== "production" ? { children: PropTypes.node.isRequired } : {}; export default StrikeThrough; //# sourceMappingURL=StrikeThrough.js.map
src/img/icon_dash.js
mikah1337/null-terminator
import React from 'react'; export default class Icon_Dash extends React.Component { constructor(props) { super(props); this.state = { height: this.props.height || "70%", color: this.props.color || "#7f8086" } } render() { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 29.99" height={this.state.height} width={this.state.height} aria-labelledby="Profile"> <g id="Layer_2" data-name="Layer 2"> <g id="Layer_1-2" data-name="Layer 1"><rect width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/> <rect x="11.25" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/><rect x="22.5" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/> <rect y="11.25" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/><rect x="11.25" y="11.25" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/> <rect x="22.5" y="11.25" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/><rect y="22.5" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/> <rect x="11.25" y="22.5" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/><rect x="22.5" y="22.5" width="7.5" height="7.5" rx="1.59" ry="1.59" fill={this.state.color}/> </g> </g> </svg> ) } }
examples/optgroup.js
ddcat1115/select
/* eslint no-console: 0 */ import React from 'react'; import Select, { Option, OptGroup } from 'rc-select'; import 'rc-select/assets/index.less'; import ReactDOM from 'react-dom'; function onChange(value) { console.log(`selected ${value}`); } const c1 = ( <div> <h2>Select OptGroup</h2> <div style={{ width: 300 }}> <Select placeholder="placeholder" defaultValue="lucy" showSearch={false} style={{ width: 500 }} onChange={onChange} > <OptGroup label="manager"> <Option value="jack"> <b style={{ color: 'red', }} > jack </b> </Option> <Option value="lucy">lucy</Option> </OptGroup> <OptGroup label="engineer"> <Option value="yiminghe">yiminghe</Option> </OptGroup> </Select> </div> </div> ); ReactDOM.render(c1, document.getElementById('__react-content'));
src/svg-icons/action/backup.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBackup = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); ActionBackup = pure(ActionBackup); ActionBackup.displayName = 'ActionBackup'; ActionBackup.muiName = 'SvgIcon'; export default ActionBackup;
test/components/AnotherHigherOrderComponent.js
naoufal/higher-order
import React, { Component } from 'react'; export default function AnotherHigherOrderComponent(ComposedComponent) { class AnotherHigherOrderComponent extends Component { render() { return ( <div style={this.props.styles}> Another Higher Order Component (passes this.props.greeting) <ComposedComponent {...this.props} greeting="Hi there!" /> </div> ); } } AnotherHigherOrderComponent.displayName = `AnotherHigherOrderComponent(${ComposedComponent.displayName})`; return AnotherHigherOrderComponent; }
src/react-loader-advanced.js
nygardk/react-loader-advanced
/* eslint-disable prefer-template, quote-props, no-underscore-dangle, react/require-default-props, react/forbid-prop-types */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'; import EventEmitter from 'wolfy87-eventemitter'; function uid() { return Math.random().toString(36).substr(2, 9); } const backgroundDefaultStyle = { display: 'block', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0,0.5)', zIndex: 10, }; const foregroundDefaultStyle = { display: 'table', width: '100%', height: '100%', textAlign: 'center', zIndex: 20, color: 'white', }; const messageDefaultStyle = { display: 'table-cell', verticalAlign: 'middle', }; export const createLoaderStack = () => ({ ...EventEmitter.prototype, stack: [], addLoader(id, priority = 0) { if (this.getIndex(id) === -1) { this.stack.push({ id, priority }); this.emitChange(); } }, removeLoader(id) { if (this.getIndex(id) !== -1) { this.stack.splice(this.getIndex(id), 1); this.emitChange(); } }, getIndex(id) { return this.stack.findIndex(loader => loader.id === id); }, getMaxPriority() { let max = 0; Object.keys(this.stack).forEach((key) => { if (this.stack[key].priority > max) { max = this.stack[key].priority; } }); return max; }, emitChange() { this.emit('change'); }, addChangeListener(callback) { this.on('change', callback); }, removeChangeListener(callback) { this.removeListener('change', callback); }, }); const createLoader = loaderStack => class Loader extends Component { static propTypes = { backgroundStyle: PropTypes.object, children: PropTypes.node, className: PropTypes.string, // blur loader content while loading contentBlur: PropTypes.number, contentStyle: PropTypes.object, // disables all default styles if true disableDefaultStyles: PropTypes.bool, foregroundStyle: PropTypes.object, hideContentOnLoad: PropTypes.bool, // loader message or element message: PropTypes.node, messageStyle: PropTypes.object, // stack priority priority: PropTypes.number, show: PropTypes.bool.isRequired, style: PropTypes.object, transitionConfig: PropTypes.shape({ transitionName: PropTypes.string.isRequired, transitionEnterTimeout: PropTypes.number.isRequired, transitionLeaveTimeout: PropTypes.number.isRequired, }), } static defaultProps = { message: 'loading...', priority: 0, } state = { active: false, } componentWillMount() { this._stackId = uid(); } componentDidMount() { loaderStack.addChangeListener(this.onStackChange); this.initialize(this.props); } componentWillReceiveProps(nextProps) { this.initialize(nextProps); } componentWillUnmount() { loaderStack.removeChangeListener(this.onStackChange); // Bugfix: 3.3.2016 // setTimeout fixes rare bug with React 0.13 that is caused by unpredictable // component lifecycle (Uncaught Error: Invariant Violation: // must be mounted to trap events). setTimeout(() => { loaderStack.removeLoader(this._stackId); }); } onStackChange = () => { // if (this.isMounted()) { this.setState({ active: loaderStack.getMaxPriority() === this.props.priority, }); // } } initialize = (props) => { if (props.show) { loaderStack.addLoader(this._stackId, props.priority); } else { loaderStack.removeLoader(this._stackId); } } render() { const { backgroundStyle, children, className, contentBlur, contentStyle, disableDefaultStyles, foregroundStyle, hideContentOnLoad, message, messageStyle, style, show, transitionConfig, } = this.props; const { active, } = this.state; const shouldShowLoader = !!active && !!show; const bgStyle = { ...(disableDefaultStyles ? {} : backgroundDefaultStyle), ...backgroundStyle, }; const fgStyle = { ...(disableDefaultStyles ? {} : foregroundDefaultStyle), ...foregroundStyle, }; const msgStyle = { ...(disableDefaultStyles ? {} : messageDefaultStyle), ...messageStyle, }; const loaderStyle = { position: 'relative', ...style }; const finalContentStyle = Object.assign(shouldShowLoader && contentBlur ? { 'WebkitFilter': `blur(${contentBlur}px)`, 'MozFilter': `blur(${contentBlur}px)`, 'OFilter': `blur(${contentBlur}px)`, 'msFilter': `blur(${contentBlur}px)`, 'filter': `blur(${contentBlur}px)`, } : {}, contentStyle, { opacity: hideContentOnLoad && show ? 0 : 1, }); const classes = 'Loader' + (className ? (' ' + className) : ''); const loaderElement = !!shouldShowLoader && ( <div className="Loader__background" style={bgStyle}> <div className="Loader__foreground" style={fgStyle}> <div className="Loader__message" style={msgStyle}> {message} </div> </div> </div> ); return ( <div className={classes} style={loaderStyle}> <div className="Loader__content" style={finalContentStyle}> {children} </div> {transitionConfig ? ( <CSSTransitionGroup {...transitionConfig}> {loaderElement} </CSSTransitionGroup> ) : loaderElement} </div> ); } }; export default createLoader(createLoaderStack());
app/user/profile/UnselectedProfileSkillListItem.js
in42/internship-portal
import React from 'react'; import { Label, Icon } from 'semantic-ui-react'; import PropTypes from 'prop-types'; export default class UnselectedProfileSkillListItem extends React.Component { constructor() { super(); this.handleClick = (event, data) => { console.log(data.children[0].props.children); this.props.restoreSkill(data.children[0].props.children); }; } render() { return ( <Label onClick={this.handleClick} key={this.props.skill} className="hover-add-label" as="a" > <span className="hover-label-text">{this.props.skill}</span> <Icon className="hover-visible" name="checkmark" /> </Label> ); } } UnselectedProfileSkillListItem.propTypes = { skill: PropTypes.string.isRequired, restoreSkill: PropTypes.func.isRequired, };
docs/app/Examples/elements/Label/Groups/LabelExampleGroupTag.js
koenvg/Semantic-UI-React
import React from 'react' import { Label } from 'semantic-ui-react' const LabelExampleGroupTag = () => ( <Label.Group tag> <Label as='a'>$10.00</Label> <Label as='a'>$19.99</Label> <Label as='a'>$24.99</Label> <Label as='a'>$30.99</Label> <Label as='a'>$10.25</Label> </Label.Group> ) export default LabelExampleGroupTag
modules/RouteUtils.js
iest/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 (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const 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) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const 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' * * const 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) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const 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 }