path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
webpack/scenes/Subscriptions/Details/SubscriptionDetailInfo.js
Katello/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'react-bootstrap'; import { translate as __ } from 'foremanReact/common/I18n'; import subscriptionAttributes from './SubscriptionAttributes'; import subscriptionPurposeAttributes from './SubscriptionPurposeAttributes'; const SubscriptionDetailInfo = ({ subscriptionDetails }) => { const subscriptionLimits = (subDetails) => { const limits = []; if (subDetails.sockets) { limits.push(__('Sockets: %s').replace('%s', subDetails.sockets)); } if (subDetails.cores) { limits.push(__('Cores: %s').replace('%s', subDetails.cores)); } if (subDetails.ram) { limits.push(__('RAM: %s GB').replace('%s', subDetails.ram)); } if (limits.length > 0) { return limits.join(', '); } return ''; }; const subscriptionDetailValue = (subDetails, key) => (subDetails[key] == null ? '' : String(subDetails[key])); const formatInstanceBased = (subDetails) => { if (subDetails.instance_multiplier == null || subDetails.instance_multiplier === '' || subDetails.instance_multiplier === 0) { return __('No'); } return __('Yes'); }; return ( <div> <h2>{__('Subscription Info')}</h2> <Table> <tbody> {Object.keys(subscriptionAttributes).map(key => ( <tr key={key}> <td><b>{__(subscriptionAttributes[key])}</b></td> <td>{subscriptionDetailValue(subscriptionDetails, key)}</td> </tr> ))} <tr> <td><b>{__('Limits')}</b></td> <td>{subscriptionLimits(subscriptionDetails)}</td> </tr> <tr> <td><b>{__('Instance-based')}</b></td> <td>{formatInstanceBased(subscriptionDetails)}</td> </tr> </tbody> </Table> <h2>{__('System Purpose')}</h2> <Table> <tbody> {Object.keys(subscriptionPurposeAttributes).map(key => ( <tr key={key}> <td><b>{__(subscriptionPurposeAttributes[key])}</b></td> <td>{subscriptionDetailValue(subscriptionDetails, key)}</td> </tr> ))} </tbody> </Table> </div> ); }; SubscriptionDetailInfo.propTypes = { subscriptionDetails: PropTypes.shape({}).isRequired, }; export default SubscriptionDetailInfo;
examples/with-relay-modern/lib/RelayProvider.js
arunoda/next.js
import React from 'react' import PropTypes from 'prop-types' // Thank you https://github.com/robrichard // https://github.com/robrichard/relay-context-provider class RelayProvider extends React.Component { getChildContext () { return { relay: { environment: this.props.environment, variables: this.props.variables } } } render () { return this.props.children } } RelayProvider.childContextTypes = { relay: PropTypes.object.isRequired } RelayProvider.propTypes = { environment: PropTypes.object.isRequired, variables: PropTypes.object.isRequired, children: PropTypes.node } export default RelayProvider
src/components/AddProduct.js
ValentinAlexandrovGeorgiev/iStore
import React, { Component } from 'react'; import ajax from 'superagent'; import SERVER_URL from '../config'; class AddProduct extends Component { constructor(props) { super(props); this.state = { message: '', quantity: this.props.quantity }; this.addToBasket = this.addToBasket.bind(this); } deleteMessage() { let that = this; setTimeout(() => { that.setState({ message: '' }); }, 3000) } addToBasket() { let product = this.props.product; let currentUserId = window.localStorage.getItem('profile-id'); let total_price = parseFloat(product.price.slice(0, product.price.length - 1)); total_price *= parseFloat(this.props.quantity); total_price = total_price.toString(); if (!currentUserId) { this.setState({ message: "Please, try to login first!" }); this.deleteMessage(); return; } ajax.post(SERVER_URL + '/basket/') .send({ user_id: currentUserId, product: product._id, color: product.color, quantity: this.props.quantity, price: total_price, ordered_by_current_user: false }) .end((err, product) => { if(!err && product) { this.setState({ message: "This product is added successfully!" }) this.deleteMessage(); } else { this.setState({ message: "There is something wrong! Please, try again after page reload" }) } }); } render() { return ( <div className="pdp-add-wrapper"> <input className="pdp-product-quantity" type="text" value={this.props.quantity} onChange={this.props.handleQuantityChange} /> <button data-id={this.props.product._id} onClick={this.addToBasket} className="pdp-add-product">Add Product</button> <p className="product-message">{this.state.message}</p> </div> ) } } export default AddProduct;
lib/ui/components/Settings/Settings.js
500tech/bdsm
import React from 'react'; import Frame from 'ui/components/common/Frame'; import { trackEvent } from 'ui/Analytics'; import SettingsState from 'ui/states/SettingsState'; import { connectToState } from 'ui/states/connector'; import ImportSection from 'ui/components/Settings/ImportSection'; import ExportSection from 'ui/components/Settings/ExportSection'; import SettingsSection from 'ui/components/Settings/SettingsSection'; import { SettingsContainer } from 'ui/components/Settings/styled'; class Settings extends React.Component { componentDidMount() { trackEvent('open settings'); } render() { return ( <Frame> <SettingsContainer> <ImportSection importSuccess={ SettingsState.importSuccess } importFailed={ SettingsState.importFailed } error={ SettingsState.error }/> <ExportSection/> <SettingsSection/> </SettingsContainer> </Frame> ); } } export default connectToState(SettingsState, Settings);
src/components/Helmet.js
radubrehar/evanghelic.ro
import React from 'react'; import Helmet from 'react-helmet'; const TITLE = 'Biserica Cluj - Biserica Creștină după Evanghelie'; const TheHelmet = ({ title, description } = {}) => ( <Helmet> <html lang="ro-RO" /> <title>{title ? title + ' - ' + TITLE : TITLE}</title> <meta name="theme-color" content="#00BCD4" /> <meta name="google-site-verification" content="IWAaY8Sro5jqdm-xp7TsoXt3Lvklx4w7536lsO21Jdw" /> <meta name="description" content={ description || 'Vino să îl cunoști pe Dumnezeu alături de noi! Biserica Cluj' } /> <meta name="keywords" content="cluj, biserica, creștină, evanghelie, Dumnezeu, Isus, cluj-napoca" /> </Helmet> ); export default TheHelmet;
UI/Fields/ListPicker.js
Datasilk/Dedicate
import React from 'react'; import {View, FlatList, StyleSheet, Dimensions, Alert, TouchableHighlight} from 'react-native'; import Text from 'text/Text'; import AppStyles from 'dedicate/AppStyles'; import Textbox from 'fields/Textbox'; import Picker from 'fields/Picker'; import ButtonEdit from 'buttons/ButtonEdit'; import ButtonClose from 'buttons/ButtonClose'; import ButtonSearch from 'buttons/ButtonSearch'; import ButtonCheck from 'buttons/ButtonCheck'; import ButtonAddListItem from 'buttons/ButtonAddListItem'; import DbLists from 'db/DbLists'; import Plural from 'utility/Plural'; export default class ListPicker extends React.Component{ constructor(props){ super(props); this.state = { searchlist:'', list:{ items:null, start:0, nomore:false }, total:0, searchable:false, refresh:1, refreshing:false, editing:null, editingLabel:null, editingValue:null }; //bind methods this.getList = this.getList.bind(this); this.onPressShowListModal = this.onPressShowListModal.bind(this); this.onShowListModal = this.onShowListModal.bind(this); this.onSearchListChangeText = this.onSearchListChangeText.bind(this); this.onPressSearchList = this.onPressSearchList.bind(this); this.onEndListReached = this.onEndListReached.bind(this); this.editItem = this.editItem.bind(this); this.saveItem = this.saveItem.bind(this); this.removeList = this.removeList.bind(this); this.onAddListItem = this.onAddListItem.bind(this); this.removeItem = this.removeItem.bind(this); this.onEditingChangeText = this.onEditingChangeText.bind(this); this.onEditingChangeValue = this.onEditingChangeValue.bind(this); } componentDidUpdate(prevProps){ if(this.props.refresh != prevProps.refresh){ this.setState({refresh:this.state.refresh + 1, list:{items:null, start:0, nomore:false}, refreshing:false}, () => { this.getList(); }); } } // Get List Items from Database //////////////////////////////////////////////////////////////////////////////////////////////////// paging =20 Name(){ return this.props.input != null ? this.props.input.name : this.props.name; } getList(callback){ const dbLists = new DbLists(); //get events from database if(this.state.list.nomore == true || this.state.refreshing == true){return;} this.setState({refreshing:true}, () => { //get results for list items let list = this.state.list; //first, get count of total list items const total = dbLists.GetListItems({listId:this.props.listId}).length; //next, get filtered list of items const items = dbLists.GetListItems({ start:list.start, length:this.paging, sorted:'label', descending:false, listId:this.props.listId, filtered:this.state.searchlist != '' ? 'label contains[c] "' + this.state.searchlist + '"' : null }); //mutate realm object into generic array of objects let results = items.map(item => { return {id:item.id, listId:item.listId, label:item.label, value:item.value} }); //check state for search results if(this.state.searchlist != '' && this.props.state != null && this.props.state.update != null){ const uresults = this.props.state.update.filter(a => a.label.toLowerCase().indexOf(this.state.searchlist.toLowerCase()) >= 0); if(uresults.length > 0){ //found matching items in update list const resultIds = results.map(a => a.id); for(let x = 0; x < uresults.length; x++){ //add items to results that don't already exist const item = uresults[x]; if(resultIds.indexOf(item.id) < 0){ results.push(item); } } } } //concatenate results to existing list if(list.items == null){ list.items = []; } let removeIds = []; if(this.props.state != null && this.props.state.remove != null){ removeIds = this.props.state.remove.map(a => a.id); } const allitems = list.items.concat(results).map(item => { if(this.props.state != null){ //filter out any items that exist in the state.remove array if(removeIds.indexOf(item.id) >= 0){return null;} //check for updated item in state object and replace item with updated item if(this.props.state.update != null){ const index = this.props.state.update.map(a => a.id).indexOf(item.id); if(index >= 0){ return this.props.state.update[index]; } } if(this.props.state.add != null){ const index = this.props.state.add.map(a => a.id).indexOf(item.id); if(index >= 0){ return null; } } } return item; }).filter(a => a != null); //update list settings list.items = allitems; list.start += this.paging; list.nomore = results.length < this.paging; this.setState({ list:list, refreshing:false, refresh:this.state.refresh+1, total:total, searchable:total >= this.paging }, () => { //exeute callback if(typeof callback != 'undefined'){ callback(); } }); }); } // Show Modal Window /////////////////////////////////////////////////////////////////////////////////////////////////////////////// onPressShowListModal(){ let list = this.state.list; list.start = 0; list.items = []; list.nomore = false; this.setState({list:list}, () => { this.getList(this.onShowListModal); }); } onShowListModal(){ if(this.state.list.items == null){ //get initial list items this.getList(this.onShowListModal); return; } //load modal window let data = (this.props.state != null && this.props.state.add != null ? this.props.state.add.concat(this.state.list.items) : this.state.list.items); if(this.state.searchlist != ''){ const search = this.state.searchlist.toLowerCase(); data = data.filter(a => a.label.toLowerCase().indexOf(search) >= 0); } const {height} = Dimensions.get('window'); global.Modal.setContent('Available ' + Plural(this.Name()), ( <View style={{minWidth:300}}> {this.state.searchable == true && <View style={this.styles.searchListForm}> <View style={this.styles.searchListTextbox}> <Textbox defaultValue={this.state.searchlist} style={this.styles.inputField} placeholder="Search" returnKeyType={'done'} onChangeText={this.onSearchListChangeText} maxLength={25} /> </View> <View style={this.styles.searchListButton}> <ButtonSearch onPress={this.onPressSearchList} size="smaller" color={AppStyles.textColor}/> </View> </View> } <View style={this.styles.listResults}> {data.length > 0 ? <FlatList style={{maxHeight:height - 200}} data={data} keyExtractor={item => item.label} onEndReached={this.onEndListReached} onEndReachedThreshold={0.5} extraData={this.state.refresh} renderItem={ ({item}) => { if(this.state.editing != null && this.state.editing.label == item.label){ return ( <View style={this.styles.listItemEditingContainer}> <View style={this.styles.listItemTextboxContainer}> <Textbox defaultValue={this.state.editingLabel} style={[this.styles.inputField, this.styles.editingTextbox]} returnKeyType={'done'} onChangeText={this.onEditingChangeText} maxLength={25} /> <ButtonCheck style={this.styles.buttonSave} size="xsmall" color={AppStyles.color} onPress={this.saveItem}/> </View> <View style={this.styles.listItemTextboxContainer}> <Textbox defaultValue={this.state.editingValue} style={[this.styles.inputField, this.styles.editingTextbox]} placeholder="0" returnKeyType={'done'} onChangeText={this.onEditingChangeValue} maxLength={10} /> </View> </View> ); }else{ const listItem = ( <View style={this.styles.listItemContainer}> <Text style={this.styles.listItemText}>{item.label}</Text> {this.props.editable == true && <View style={this.styles.editableContainer}> <View style={this.styles.buttonEdit}><ButtonEdit size="xxsmall" color={AppStyles.color} onPress={() => {this.editItem(item)}}/></View> <View style={this.styles.buttonRemove}><ButtonClose size="xxsmall" color={AppStyles.color} onPress={() => {this.removeItem(item)}}/></View> </View> } </View> ); if(this.props.onValueChange != null){ //selectable list item return ( <TouchableHighlight underlayColor={AppStyles.listItemPressedColor} onPress={() => {this.props.onValueChange(item); global.Modal.hide();}}> {listItem} </TouchableHighlight> ); }else{ //non-selectable list item return listItem; } } } } ></FlatList> : (this.state.total > 0 ? <View style={this.styles.noitems}> <Text style={this.styles.noitemsText}>Your search returned no results</Text> </View> : <View style={this.styles.noitems}> <Text style={this.styles.noitemsText}>This list doesn't contain any items yet</Text> </View> ) } </View> </View> ), false, true); //scrollable = false, close button = true global.Modal.show(); } // Search List Items //////////////////////////////////////////////////////////////////////////////////////////////////// onSearchListChangeText = (text) => { this.setState({searchlist:text}); } onPressSearchList(){ let list = this.state.list; list.start = 0; list.items = []; list.nomore = false; this.setState({list:list}, () => { this.getList(this.onShowListModal); }); } onEndListReached(){ this.getList(this.onShowListModal); } // Edit Item ////////////////////////////////////////////////////////////////////////////// editItem(item){ this.setState({editing:item, editingLabel:item.label, editingValue:item.value, refresh:this.state.refresh+1}, () => { this.onShowListModal(); }); } onEditingChangeText(text){ this.setState({editingLabel:text}); } onEditingChangeValue(text){ this.setState({editingValue:text != '' ? parseFloat(text) : null}); } // Save Edits to List Item //////////////////////////////////////////////////////////////////////////////////////////////////// saveItem(){ //save edits to list item let index = -1; let item = this.state.editing; let state = this.props.state || {add:[], update:[], remove:[]}; const value = this.state.editingValue != null ? parseFloat(this.state.editingValue) : null; if(state.add == null){state.add = [];} if(state.update == null){state.update = [];} if(state.remove == null){state.remove = [];} if(this.props.state != null && this.props.state.add != null){ //check add array first to see if this is a new item that hasn't been added to the database yet index = this.props.state.add.map(a => a.label).indexOf(this.state.editing.label); } if(index >= 0){ //item exists in add array state.add[index] = {label:this.state.editingLabel, value:value}; this.props.onUpdateListState(state); this.setState({editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => { this.onShowListModal(); }); }else{ //item exists in database let list = this.state.list; index = list.items.map(a => a.label).indexOf(this.state.editing.label); item = list.items[index]; item = {id:item.id, listId:item.listId, label:this.state.editingLabel, value:value}; list.items[index] = item; //make changes to props.state for update command const x = 0; if(state.update != null){ x = state.update.map(a => a.id).indexOf(item.id); if(x < 0){ x = state.update.length; } }else{ state.update = []; } if(x < state.update.length){ //found item within update array state.update[x] = item; }else{ //item isn't in update array yet state.update.push(item); } this.props.onUpdateListState(state); //update list this.setState({list:list, editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => { this.onShowListModal(); }); } } // Remove List ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// removeList(){ Alert.alert( 'Delete List', 'Do you really want to permanently delete the list "' + this.Name() + '"? This cannot be undone! All tasks that use this list will instead use an empty list, all events that use the list will display an empty value, and all charts that filter by this list will no longer use the filter.', [ {text: 'Cancel', onPress: () => {}, style: 'cancel'}, {text: 'Delete', onPress: () => { const dbLists = new DbLists(); dbLists.DeleteList(this.props.listId); if(typeof this.props.onRemoveList == 'function'){ this.props.onRemoveList(); } }} ], { cancelable: true } ); } // Add List Item //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// onAddListItem(item){ const dbLists = new DbLists(); const newitem = {listId:this.props.listId, label:item.label, value:item.value}; dbLists.CreateListItem(newitem); if(typeof this.props.onAddListItem == 'function'){ this.props.onAddListItem(newitem); } } // Remove List Item ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// removeItem(item){ Alert.alert( 'Delete List Item?', 'Do you really want to delete the list item "' + item.label + '"? This will take effect only after you save changes to this task.', [ {text: 'Cancel', style: 'cancel'}, {text: 'Delete List Item', onPress: () => { let list = this.state.list; let state = this.props.state || {add:[], update:[], remove:[]}; if(state.add == null){state.add = [];} if(state.update == null){state.update = [];} if(state.remove == null){state.remove = [];} //delete item in state.add array let index = state.add.map(a => a.label.toLowerCase()).indexOf(item.label.toLowerCase()); if(index >= 0){ state.add.splice(index, 1); } if(item.id != null){ //delete item in state.update array index = state.update.map(a => a.id).indexOf(item.id); if(index >= 0){ state.add.splice(index, 1); } //check for duplicate in state.remove array index = state.remove.map(a => a.id).indexOf(item.id); if(index < 0){ state.remove.push(item); index = list.items.map(a => a.id).indexOf(item.id); if(index >= 0){ list.items.splice(index, 1); } } } this.props.onUpdateListState(state); //update list this.setState({list:list, editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => { this.onShowListModal(); }); }} ], { cancelable: true } ) } // Render Component //////////////////////////////////////////////////////////////////////////////////////////////////// render(){ switch(this.props.view){ case 'list': return ( <TouchableHighlight underlayColor={AppStyles.listItemPressedColor} onPress={this.onPressShowListModal}> <View style={[this.styles.listItem, this.props.style]}> <Text style={[this.styles.listItemText, this.props.textStyle]}>{this.props.selectedText}</Text> {this.props.editable == true && <View style={this.styles.listItemButtons}> <View style={this.styles.listItemButton}> <ButtonAddListItem size="xxsmall" list={{name:this.Name()}} onAddListItem={this.onAddListItem} /> </View> <View style={this.styles.listItemButton}><ButtonClose size="xxsmall" color={AppStyles.color} onPress={this.removeList}/></View> </View> } </View> </TouchableHighlight> ); default: return ( <Picker {...this.props} items={['']} selectedText={this.props.selectedText || 'Select...'} onShowModal={this.onPressShowListModal} /> ); } } styles = StyleSheet.create({ //list items listItem:{flexDirection:'row', justifyContent:'space-between', padding:AppStyles.padding}, listItemText:{fontSize:AppStyles.titleFontSize}, listItemButtons:{flexDirection:'row'}, listItemButton:{paddingLeft:AppStyles.paddingLarge}, //modal window inputField: {fontSize:AppStyles.titleFontSize}, noitems:{flexDirection:'row', justifyContent:'center'}, noitemsText:{opacity:0.5, padding:AppStyles.paddingLarge}, //list items modal window searchListForm:{flexDirection:'row', justifyContent:'space-between', paddingVertical:AppStyles.padding, paddingHorizontal:AppStyles.paddingLarger}, searchListTextbox:{width:200}, searchListButton:{width:AppStyles.iconSmaller + AppStyles.padding, paddingTop:AppStyles.padding, paddingLeft:AppStyles.padding}, listItemContainer:{flexDirection:'row', justifyContent:'space-between', paddingVertical:AppStyles.padding, paddingHorizontal:AppStyles.paddingLarger, borderBottomColor: AppStyles.separatorColor, borderBottomWidth:1}, listItemEditingContainer:{paddingBottom:AppStyles.padding, borderBottomColor: AppStyles.separatorColor, borderBottomWidth:1}, listItemTextboxContainer:{flexDirection:'row', justifyContent:'space-between', paddingTop:AppStyles.paddingSmaller, paddingHorizontal:AppStyles.paddingLarger}, listItemText:{}, editableContainer:{flexDirection:'row'}, buttonEdit:{paddingRight:15}, buttonRemove:{}, buttonSave:{paddingTop:AppStyles.padding}, editingTextbox:{width:200} }) }
app/react-icons/fa/chain-broken.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaChainBroken extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m11.3 28.4l-5.7 5.7q-0.2 0.2-0.5 0.2-0.3 0-0.5-0.2-0.2-0.2-0.2-0.5t0.2-0.5l5.7-5.8q0.2-0.2 0.5-0.2t0.5 0.2q0.2 0.3 0.2 0.6t-0.2 0.5z m3.8 0.9v7.1q0 0.3-0.2 0.5t-0.5 0.2-0.6-0.2-0.2-0.5v-7.1q0-0.3 0.2-0.5t0.6-0.2 0.5 0.2 0.2 0.5z m-5-5q0 0.3-0.2 0.5t-0.5 0.2h-7.2q-0.3 0-0.5-0.2t-0.2-0.5 0.2-0.5 0.5-0.2h7.2q0.3 0 0.5 0.2t0.2 0.5z m28.2 2.8q0 2.7-1.9 4.6l-3.3 3.2q-1.8 1.9-4.5 1.9-2.7 0-4.6-1.9l-7.4-7.5q-0.5-0.5-1-1.2l5.4-0.4 6.1 6.1q0.6 0.6 1.5 0.6t1.5-0.6l3.3-3.3q0.6-0.6 0.6-1.5 0-0.9-0.6-1.5l-6.1-6.1 0.4-5.4q0.7 0.5 1.2 1l7.5 7.5q1.9 1.9 1.9 4.5z m-13.8-16.1l-5.3 0.4-6.1-6.1q-0.6-0.7-1.5-0.7-0.9 0-1.6 0.6l-3.2 3.3q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.5l6.1 6.1-0.4 5.4q-0.8-0.5-1.3-0.9l-7.5-7.5q-1.8-2-1.8-4.6 0-2.7 1.9-4.5l3.2-3.3q1.9-1.8 4.6-1.8 2.7 0 4.5 1.9l7.5 7.4q0.4 0.5 0.9 1.3z m14.1 1.9q0 0.3-0.2 0.5t-0.5 0.2h-7.1q-0.3 0-0.5-0.2t-0.2-0.5 0.2-0.6 0.5-0.2h7.1q0.3 0 0.5 0.2t0.2 0.6z m-12.1-12.2v7.2q0 0.3-0.2 0.5t-0.5 0.2-0.5-0.2-0.2-0.5v-7.2q0-0.3 0.2-0.5t0.5-0.2 0.5 0.2 0.2 0.5z m9.1 3.4l-5.7 5.7q-0.3 0.2-0.5 0.2t-0.6-0.2q-0.2-0.2-0.2-0.5t0.2-0.5l5.8-5.7q0.2-0.2 0.5-0.2t0.5 0.2q0.2 0.2 0.2 0.5t-0.2 0.5z"/></g> </IconBase> ); } }
go-betz/src/components/Bet/index.js
FabioFischer/go-betz
import React from 'react'; import { Card, CardTitle, CardText } from 'material-ui'; class Bet extends React.Component { state = { expanded: false }; render() { const { match, pick, value } = this.props; const { description, teamA, teamB, winner } = match; let expandedDescription = `I bet ${value} credits on ${pick.name}. `; if (winner) { if (winner.id === teamA.id) teamA.name = `👑 ${teamA.name} 👑`; if (winner.id === teamB.id) teamB.name = `👑 ${teamB.name} 👑`; if (winner.id === pick.id) expandedDescription = expandedDescription.concat('I won the bet 🤑'); else expandedDescription = expandedDescription.concat(`I lost the bet 😔`); } return ( <Card> <CardTitle title={`${teamA.name} vs. ${teamB.name}`} subtitle={description} actAsExpander={true} showExpandableButton={true} /> <CardText expandable={true}> <CardTitle title={expandedDescription} /> </CardText> </Card> ); } } export default Bet;
node_modules/react-router/es/IndexRedirect.js
ProjectSunday/rooibus
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import Redirect from './Redirect'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes, string = _React$PropTypes.string, object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ /* eslint-disable react/require-render-return */ var IndexRedirect = React.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRedirect;
newclient/scripts/components/config/general/disclosure-type/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import EditLink from '../../edit-link'; import DoneLink from '../../done-link'; import ConfigActions from '../../../../actions/config-actions'; export default class DisclosureType extends React.Component { constructor() { super(); this.state = { editing: false }; this.editType = this.editType.bind(this); this.doneEditing = this.doneEditing.bind(this); this.keyUp = this.keyUp.bind(this); this.toggle = this.toggle.bind(this); } toggle() { const checkbox = this.refs.checkbox; if (checkbox.checked) { ConfigActions.enableDisclosureType(this.props.type.typeCd); } else { ConfigActions.disableDisclosureType(this.props.type.typeCd); } } keyUp(evt) { if (evt.keyCode === 13) { this.doneEditing(); } } editType() { this.setState({ editing: true }); } doneEditing() { const textbox = this.refs.label; ConfigActions.updateDisclosureType(this.props.type.typeCd, textbox.value); this.setState({ editing: false }); } render() { let jsx; if (this.state.editing) { jsx = ( <span className={styles.dynamicSpan}> <input type="text" ref="label" className={styles.textbox} defaultValue={this.props.type.description} onKeyUp={this.keyUp} /> <DoneLink onClick={this.doneEditing} className={`${styles.override} ${styles.editLink}`} /> </span> ); } else { jsx = ( <span className={styles.dynamicSpan}> <label htmlFor={`${this.props.type.typeCd}disctype`} className={styles.label} > {this.props.type.description} </label> <EditLink onClick={this.editType} className={`${styles.override} ${styles.editLink}`} /> </span> ); } let checkbox; if (this.props.canToggle) { checkbox = ( <input ref="checkbox" id={`${this.props.type.typeCd}disctype`} type="checkbox" className={styles.checkbox} checked={this.props.type.enabled === 1} onChange={this.toggle} /> ); } return ( <span className={`fill ${this.props.className}`}> {checkbox} {jsx} </span> ); } }
node_modules/rc-table/es/TableCell.js
yhx0634/foodshopfront
import _extends from 'babel-runtime/helpers/extends'; 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 get from 'lodash.get'; var TableCell = function (_React$Component) { _inherits(TableCell, _React$Component); function TableCell() { var _ref; var _temp, _this, _ret; _classCallCheck(this, TableCell); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = TableCell.__proto__ || Object.getPrototypeOf(TableCell)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) { var _this$props = _this.props, record = _this$props.record, onCellClick = _this$props.column.onCellClick; if (onCellClick) { onCellClick(record, e); } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(TableCell, [{ key: 'isInvalidRenderCellText', value: function isInvalidRenderCellText(text) { return text && !React.isValidElement(text) && Object.prototype.toString.call(text) === '[object Object]'; } }, { key: 'render', value: function render() { var _props = this.props, record = _props.record, indentSize = _props.indentSize, prefixCls = _props.prefixCls, indent = _props.indent, index = _props.index, expandIcon = _props.expandIcon, column = _props.column; var dataIndex = column.dataIndex, render = column.render, _column$className = column.className, className = _column$className === undefined ? '' : _column$className; // We should return undefined if no dataIndex is specified, but in order to // be compatible with object-path's behavior, we return the record object instead. var text = void 0; if (typeof dataIndex === 'number') { text = get(record, dataIndex); } else if (!dataIndex || dataIndex.length === 0) { text = record; } else { text = get(record, dataIndex); } var tdProps = void 0; var colSpan = void 0; var rowSpan = void 0; if (render) { text = render(text, record, index); if (this.isInvalidRenderCellText(text)) { tdProps = text.props || {}; colSpan = tdProps.colSpan; rowSpan = tdProps.rowSpan; text = text.children; } } // Fix https://github.com/ant-design/ant-design/issues/1202 if (this.isInvalidRenderCellText(text)) { text = null; } var indentText = expandIcon ? React.createElement('span', { style: { paddingLeft: indentSize * indent + 'px' }, className: prefixCls + '-indent indent-level-' + indent }) : null; if (rowSpan === 0 || colSpan === 0) { return null; } return React.createElement( 'td', _extends({ className: className }, tdProps, { onClick: this.handleClick }), indentText, expandIcon, text ); } }]); return TableCell; }(React.Component); TableCell.propTypes = { record: PropTypes.object, prefixCls: PropTypes.string, index: PropTypes.number, indent: PropTypes.number, indentSize: PropTypes.number, column: PropTypes.object, expandIcon: PropTypes.node }; export default TableCell;
lib/editor/containers/ImageManagerApp.js
jirokun/survey-designer-js
/* eslint-env browser */ import React, { Component } from 'react'; import $ from 'jquery'; import classNames from 'classnames'; import { List } from 'immutable'; import Spinner from 'react-spinkit'; import ImageManager from '../components/editors/ImageManager'; import '../css/bootstrap.less'; /** * ImageManagerのアプリ * * TinyMCEからも画像管理からも使うので、プレーンなReactコンポーネントとして実装する。Reduxは使わない */ export default class ImageManagerApp extends Component { constructor(props) { super(props); this.state = { imageList: List(), // 画像のリスト loading: false, // ロード中 }; } componentDidMount() { this.loadImages(); } loadImages() { const { options } = this.props; this.setState({ loading: true }); $.ajax({ url: options.imageListUrl, dataType: 'json', }).done((json) => { this.setState({ imageList: List(json) }); }).fail((error) => { console.log(error); alert('画像の一覧取得に失敗しました'); }).always(() => { this.setState({ loading: false }); }); } uploadImages(formData) { const { options } = this.props; this.setState({ loading: true }); $.ajax({ url: options.uploadImageUrl, method: 'POST', data: formData, processData: false, contentType: false, dataType: 'json', }).done((res) => { if (res.error) { alert(res.message); } else { res.imageList.forEach(image => this.setState({ imageList: this.state.imageList.unshift(image) })); } }).fail(() => { alert('ファイルのアップロードに失敗しました'); }).always(() => { this.setState({ loading: false }); }); } deleteImage(image) { if (!confirm('本当に削除しますか?')) return; const { options } = this.props; const imageId = image._id; this.setState({ loading: true }); $.ajax({ url: `${options.deleteImageUrl}?docId=${imageId}`, method: 'POST', data: { imageId }, dataType: 'json', }).done(() => { this.setState({ imageList: this.state.imageList.filter(img => img.id !== image.id) }); }).fail(() => { alert('ファイルの削除に失敗しました'); }).always(() => { this.setState({ loading: false }); }); } handleInsertImage(params) { window.parent.postMessage({ type: 'insertImage', value: JSON.stringify(params) }, '*'); } render() { return ( <div className="image-manager" style={{ paddingLeft: '8px' }}> <ImageManager uploadImagesFunc={formData => this.uploadImages(formData)} insertImageFunc={params => this.handleInsertImage(params)} deleteImageFunc={image => this.deleteImage(image)} imageList={this.state.imageList} /> <div className={classNames({ hidden: !this.state.loading })}> <div className="image-manager-block-layer" /> <div className="image-manager-spinner"> <Spinner name="ball-triangle-path" color="aqua" /> </div> </div> </div> ); } }
src/App.js
GuillaumeRahbari/react-website
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } } export default App;
webpack/scenes/ModuleStreams/Details/Profiles/ModuleStreamDetailProfiles.js
mccun934/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'patternfly-react'; import TableSchema from './TableSchema'; const ModuleStreamDetailProfiles = ({ profiles }) => ( <div> <Table.PfProvider columns={TableSchema}> <Table.Header /> <Table.Body rows={profiles} rowKey="id" /> </Table.PfProvider> </div> ); ModuleStreamDetailProfiles.propTypes = { profiles: PropTypes.arrayOf(PropTypes.shape({})).isRequired, }; export default ModuleStreamDetailProfiles;
src/routes/BusinessPage/UDingHuo/index.js
janeluck/red
/** * Created by janeluck on 17/6/19. */ import React from 'react' import {Steps, Button, Form, Input} from 'antd'; import _ from 'lodash' import styles from './index.less' import MappingTable from '../MappingTable' const Step = Steps.Step; const FormItem = Form.Item; const steps = ['企业', '人员', '客户'] // 企业的对应表单项 const corporationItems = [ { label: 'U订货平台的企业名称', name: 'U' }, { label: 'Key', name: 'K' }, { label: 'Secret', name: 'S' }, { label: 'Token', name: 'T' } ] export default class extends React.Component { constructor(props) { super(props) this.state = { current: 0, } } prev = () => { let current = this.state.current - 1; this.setState({current}); } next = () => { let current = this.state.current + 1; this.setState({current}); } render() { const {current} = this.state; const that = this let First = class extends React.Component { constructor(props) { super(props) } handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { console.log('Received values of form: ', values); if (!err) { console.log('Received values of form: ', values); that.next() } }); } render() { const formItemLayout = { labelCol: {span: 6}, wrapperCol: {span: 18}, }; const {getFieldDecorator} = this.props.form; // attrType 可为String, Number类型。 传入的时候统一处理为Number return (<div> <Form onSubmit={this.handleSubmit} className={styles.corporationForm}> { _.map(corporationItems, item => { return <FormItem {...formItemLayout} key={item.name} label={item.label} > {getFieldDecorator(item.name, { rules: [{required: true, message: `${item.name}不能为空`}], })( <Input style={{width: "300px"}}/> )} </FormItem> }) } <FormItem wrapperCol={{span: 12, offset: 6}} > <Button type="primary" htmlType="submit">下一步</Button> </FormItem> </Form> </div> ) } } return ( <div> <div style={{marginBottom: 24}}>当前正在执行第 {current + 1} 步</div> <Steps current={current}> {_.map(steps, (s, i) => <Step key={i} title={`${s}的对应`}/>)} </Steps> {current == 0 && React.createElement(Form.create()(First))} {current == 1 && <MappingTable />} {current == 2 && <MappingTable />} <div style={{marginTop: 24}}> {current > 0 && <Button onClick={this.prev} disabled={current == 0}>上一步</Button>} {current < steps.length - 1 && <Button onClick={this.next}>下一步</Button>} </div> </div> ); } }
app/javascript/components/collections/list/ButtonCollectionListShowAll.js
avalonmediasystem/avalon
/* * Copyright 2011-2022, The Trustees of Indiana University and Northwestern * University. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * --- END LICENSE_HEADER BLOCK --- */ import React from 'react'; import PropTypes from 'prop-types'; const ButtonCollectionListShowAll = ({ collectionsLength, maxItems, handleShowAll, showAll }) => { if (collectionsLength > maxItems) { return ( <button aria-controls="collections-list-remaining-collections" aria-expanded={showAll} onClick={handleShowAll} className="btn btn-link show-all" role="button" > <i className={`fa ${showAll ? 'fa-chevron-down' : 'fa-chevron-right'}`} /> {` Show ${showAll ? `less` : `${collectionsLength} items`}`} </button> ); } return null; }; ButtonCollectionListShowAll.propTypes = { collectionsLength: PropTypes.number, maxItems: PropTypes.number, handleShowAll: PropTypes.func, showAll: PropTypes.bool }; export default ButtonCollectionListShowAll;
src/frontend/src/components/counters/RoundCount.js
ziroby/dmassist
import React from 'react'; import './RoundCount.css'; function RoundCount(props) { return ( <div className="RoundCount"> round:&nbsp;{props.round} </div> ); } export default RoundCount;
src/routes.js
transmute-industries/eth-faucet
import React from 'react' import { Route, IndexRoute, Redirect } from 'react-router' import { DEBUG_PATH as DebugRoute, CREATE_FAUCET_PATH as CreateFaucetRoute, NAME_FAUCET_PATH as FaucetRoute, AUTHORIZE_FAUCET_PATH as AuthorizeFaucetRoute } from './constants/paths' import CoreLayout from './layouts/CoreLayout/CoreLayout' import HomePage from './components/HomePage' import DebugFormContainer from './containers/DebugFormContainer' import CreateFaucetPage from './components/CreateFaucetPage' import FaucetPage from './components/FaucetPage' import AuthorizeFaucetPage from './components/AuthorizeFaucetPage' import { getFaucetByName } from './store/ethereum/faucet/actions' const routes = (store) => { const fetchFaucet = () => { let faucetName = getFaucetNameFromPath(window.location.pathname) if (faucetName) { store.dispatch(getFaucetByName(faucetName)) } } const getFaucetNameFromPath = (path) => { if (pathContainsFaucet(path)) { var parts = decodeURI(path).split('/') let cleanName = parts[2].toLowerCase().replace(/\s+/g, '-') return cleanName } return null } const pathContainsFaucet = (pathname) => { return pathname.indexOf('/faucets/') !== -1 } return ( <Route path='/' component={CoreLayout}> <IndexRoute component={HomePage} /> <Route path={DebugRoute} component={DebugFormContainer} /> <Route path={CreateFaucetRoute} component={CreateFaucetPage} /> <Route path={FaucetRoute} component={FaucetPage} onEnter={fetchFaucet} /> <Route path={AuthorizeFaucetRoute} component={AuthorizeFaucetPage} /> <Redirect from='*' to='/' /> </Route> ) } export default routes
services/web/client/containers/search.js
apparatus/mu-app
'use strict' import React from 'react' import {connect} from 'react-redux' import {search} from '../actions/search' import {SearchResult} from '../components/search-result' import { Row, Col, RowCol } from '../components/layout' export const Home = React.createClass({ propTypes: { dispatch: React.PropTypes.func.isRequired }, handleSearch (event) { event.preventDefault() const {query} = this.refs const {dispatch} = this.props dispatch(search(query.value)) }, render () { let query = this.props.query let items = this.props.result let body = null if (!items || items.length <= 0) { body = ( query ? <div className="alert alert-info alert-has-icon txt-left"> <p className="m0">No results found for: {query}</p> </div> : '' ) } else { body = items.map((item) => { return <SearchResult key={item.name} data={item} /> }) } return ( <Col xs={12}> <RowCol rowClass="center-xs" colElement='form' id="query-form" xs={12} md={8} className="panel" onSubmit={this.handleSearch}> <Row> <Col xs={12} sm={8}> <input ref="query" type="search" placeholder="Module Name" id="query-term" className="input-large" /> </Col> <Col xs={12} sm={4}> <button id="query-submit" type="submit" className="btn btn-large">Search</button> </Col> </Row> </RowCol> <Row className="center-xs"> {body} </Row> </Col> ) } }) function mapStatesToProps (state) { return { query: state.search.query, result: state.search.result } } export default connect(mapStatesToProps)(Home)
src/routes.js
SWTPAIN/react-redux-universal-hot-example
import React from 'react'; import {Route} from 'react-router'; import { App, Home, Widgets, About, Login, RequireLogin, LoginSuccess, Survey, NotFound, } from 'containers'; export default function(store) { return ( <Route component={App}> <Route path="/" component={Home}/> <Route path="/widgets" component={Widgets}/> <Route path="/about" component={About}/> <Route path="/login" component={Login}/> <Route component={RequireLogin} onEnter={RequireLogin.onEnter(store)}> <Route path="/loginSuccess" component={LoginSuccess}/> </Route> <Route path="/survey" component={Survey}/> <Route path="*" component={NotFound}/> </Route> ); }
src/svg-icons/maps/local-convenience-store.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalConvenienceStore = (props) => ( <SvgIcon {...props}> <path d="M19 7V4H5v3H2v13h8v-4h4v4h8V7h-3zm-8 3H9v1h2v1H8V9h2V8H8V7h3v3zm5 2h-1v-2h-2V7h1v2h1V7h1v5z"/> </SvgIcon> ); MapsLocalConvenienceStore = pure(MapsLocalConvenienceStore); MapsLocalConvenienceStore.displayName = 'MapsLocalConvenienceStore'; MapsLocalConvenienceStore.muiName = 'SvgIcon'; export default MapsLocalConvenienceStore;
src/components/Header.js
amit-kulkarni/react-food-order
import React from 'react'; export default function Header(props) { return ( <div className="container header"> <div className="row align-items-center py-3"> <div className="col-md-10"> <h3> <i className="fa fa-cutlery mr-3" aria-hidden="true"></i> <span>Order Food</span> </h3> </div> <div className="col-md-2"> <i className="fa fa-shopping-cart mr-1"></i> <span style={{ fontSize: "0.75rem" }}>{props.orderCount}</span> </div> </div> </div > ); }
src/core/scenes.js
CharlesMangwa/Chloe
/* @flow */ import React from 'react' import { Actions, Scene } from 'react-native-router-flux' import { AdvertScene } from '@Advert/scenes' import { ThemesScene } from '@Themes/scenes' import { ChaptersScene } from '@Chapters/scenes' import { StoryOverviewScene } from '@StoryOverview/scenes' import { StoryScene } from '@Story/scenes' export default Actions.create( <Scene key="root" hideNavBar={true}> <Scene key="themes" component={ThemesScene} title="Themes" /> <Scene key="advert" component={AdvertScene} title="Advert" /> <Scene key="chapters" component={ChaptersScene} title="Chapters" /> <Scene key="storyOverview" component={StoryOverviewScene} title="Story Overview" /> <Scene key="story" component={StoryScene} title="Story" /> </Scene> )
react/src/components/ThumbnailSizes/index.js
sinfin/folio
import React from 'react' import ThumbnailSize from './ThumbnailSize' function ThumbnailSizes ({ file, updateThumbnail }) { const thumbnailSizes = file.attributes.thumbnail_sizes if (!thumbnailSizes) return null const keys = Object.keys(thumbnailSizes) if (keys.length === 0) return null return ( <React.Fragment> <h4 className='mt-0'>{window.FolioConsole.translations.thumbnailSizes}</h4> <div className='d-flex flex-wrap'> {keys.map((key) => <ThumbnailSize key={key} thumbKey={key} thumb={thumbnailSizes[key]} file={file} updateThumbnail={updateThumbnail} />)} </div> </React.Fragment> ) } export default ThumbnailSizes
examples/03 - Basic auth/components/Dashboard.js
Kureev/browserify-react-live
import React from 'react'; import auth from '../vendor/auth'; export default class Dashboard extends React.Component { render() { var token = auth.getToken(); return ( <div> <h1>Dashboard</h1> <p>You made it!</p> <p>{token}</p> </div> ); } }
ext/lib/site/auth-facebook/confirm/component.js
RosarioCiudad/democracyos
import React from 'react' export default () => { const user = window.initialState.authFacebookConfirmUser return ( <div className='container-simple ext-auth-facebook-confirm'> <p className='title'>Ingresar como:</p> <div className='avatar'> <img src={user.avatar} alt={user.displayName} /> <i className='icon-social-facebook' /> </div> <h3 className='name'>{user.displayName}</h3> <a href='/auth/facebook' className='confirm btn btn-block btn-success'> Ingresar </a> </div> ) }
node_modules/react-router/es6/RoutingContext.js
superKaigon/TheCave
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
JotunheimenPlaces/src/components/Button.js
designrad/Jotunheimen-tracking
import React, { Component } from 'react'; import ReactNative from 'react-native'; const { StyleSheet, Text, View, TouchableOpacity } = ReactNative; /** * Button component */ export default class Button extends Component { /** * Render a Button * @return {jsxresult} result in jsx format */ render() { return ( <TouchableOpacity style={styles.button} onPress={this.props.onPress}> <Text style={styles.whiteFont}>{this.props.children}</Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ button: { backgroundColor: '#01743D', padding: 15, alignItems: 'center', borderWidth: 0 }, whiteFont: { color: '#fff', fontFamily: 'Roboto-Light', fontSize: 20 } });
lib/ui/src/containers/preview.js
storybooks/react-storybook
import { PREVIEW_URL } from 'global'; import React from 'react'; import { Consumer } from '@storybook/api'; import { Preview } from '../components/preview/preview'; const nonAlphanumSpace = /[^a-z0-9 ]/gi; const doubleSpace = /\s\s/gi; const replacer = match => ` ${match} `; const addExtraWhiteSpace = input => input.replace(nonAlphanumSpace, replacer).replace(doubleSpace, ' '); const getDescription = (storiesHash, storyId) => { const storyInfo = storiesHash[storyId]; return storyInfo ? addExtraWhiteSpace(`${storyInfo.kind} - ${storyInfo.name}`) : ''; }; const mapper = ({ api, state: { layout, location, customQueryParams, storiesHash, storyId } }) => { const story = storiesHash[storyId]; return { api, getElements: api.getElements, options: layout, description: getDescription(storiesHash, storyId), ...api.getUrlState(), queryParams: customQueryParams, docsOnly: story && story.parameters && story.parameters.docsOnly, location, }; }; function getBaseUrl() { try { return PREVIEW_URL || 'iframe.html'; } catch (e) { return 'iframe.html'; } } const PreviewConnected = React.memo(props => ( <Consumer filter={mapper}> {fromState => { return ( <Preview {...props} baseUrl={getBaseUrl()} {...fromState} customCanvas={fromState.api.renderPreview} /> ); }} </Consumer> )); PreviewConnected.displayName = 'PreviewConnected'; export default PreviewConnected;
examples/huge-apps/app.js
axross/react-router
/*eslint-disable no-unused-vars */ import React from 'react' import { createHistory, useBasename } from 'history' import { Router } from 'react-router' import stubbedCourses from './stubs/COURSES' const history = useBasename(createHistory)({ basename: '/huge-apps' }) const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile') ] } ] } React.render( <Router history={history} routes={rootRoute} />, document.getElementById('example') ) // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like // // import { Route } from 'react-router' // import App from './components/App' // import Course from './routes/Course/components/Course' // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar' // import Announcements from './routes/Course/routes/Announcements/components/Announcements' // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement' // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar' // import Assignments from './routes/Course/routes/Assignments/components/Assignments' // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment' // import CourseGrades from './routes/Course/routes/Grades/components/Grades' // import Calendar from './routes/Calendar/components/Calendar' // import Grades from './routes/Grades/components/Grades' // import Messages from './routes/Messages/components/Messages' // React.render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // )
routes/Statistic/components/DotInfo.js
YongYuH/Ludo
import React from 'react'; import styled from 'styled-components'; import { translate } from 'react-i18next'; import Card from './Card'; import Button from '../../../components/Button'; const ButtonWrapper = styled.div` margin-top: 10px; `; const Wrapper = styled.div` `; const DotInfo = ({ t, }) => ( <Wrapper> <Card /> <ButtonWrapper> <Button backgroundColor="#2fa0dd" label={t('show reportList')} /> </ButtonWrapper> </Wrapper> ); export default translate(['statistic'])(DotInfo);
client/components/Layout/Layout.js
kriasoft/FSharp-Server-Template
/** * ASP.NET Core Starter Kit * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Header from './Header'; import s from './Layout.css'; class Layout extends React.Component { componentDidMount() { window.componentHandler.upgradeElement(this.refs.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.refs.root); } render() { return ( <div className="mdl-layout mdl-js-layout" ref="root"> <div className="mdl-layout__inner-container"> <div className={s.ribbon}> <Header /> <div className={s.container}> <h1 className={`mdl-typography--title ${s.tagline}`}>ASP.NET Core Starter Kit</h1> <p className={`mdl-typography--body-1 ${s.summary}`}> Single-page application boilerplate powered by .NET Core and React </p> </div> </div> <main {...this.props} className={s.content} /> </div> </div> ); } } export default Layout;
src/components/Lottery/Lottery.js
febobo/react-redux-start
import React from 'react' import dynamicIco from '../../static/images/dynamicIco.png' import aboutIco from '../../static/images/aboutIco.png' import classes from '../Lottery/Lottery.scss' import {i18n} from '../../util/i18n' import { getBtcWebsocket , btcWebsocket } from '../../actions/Websocket' import { connect } from 'react-redux' import { Alert , Table ,Tag } from 'antd' import moment from 'moment' type Props = { }; export class Lottery extends React.Component { props: Props; componentWillMount (){ // this._stream() const { getBtcWebsocket , btcWebsocket } = this.props; getBtcWebsocket() // btcWebsocket({name : 1}) } componentDidMount (){ // let warp = document.getElementById('listScroll'); // console.log(warp.scrollTop) // setInterval( () =>{ // if(warp.scrollTop >= 105){ // warp.scrollTop =0; // }else { // warp.scrollTop ++ ; // } // },100) } render () { const { users_online , latest_incomes } = this.props.lottery; const { isDynamic , style } = this.props; // const list = latest_incomes && latest_incomes.length && latest_incomes.map( (v, k) => { // return ( // <div key={'lottery' + k }> // <div>{v.address}</div> // <div>{v.amount}</div> // <div>{moment(v.time).format("YYYY-MM-DD hh:mm:ss")}</div> // </div> // ) // }) const columns = [{ title: i18n.t('common.btcAddress'), dataIndex: 'address', render(text) { return <a href="#">{text}</a>; } }, { title: i18n.t('common.amount'), dataIndex: 'amount' }, { title: i18n.t('common.time'), dataIndex: 'time' }]; const data = []; latest_incomes && latest_incomes.length && latest_incomes.map( (v, k) => { data.push({ key: `${k}`, address: `${v.address}`, amount: <Tag color="blue">{v.amount.toFixed(8)}</Tag>, time: moment(Date.parse(`${v.time}`)).format("YYYY-MM-DD HH:mm:ss"), }); }) return ( <div className={classes.dynamic} style={style}> { isDynamic ? null : <div className={classes.dynamicTitle}><img src={dynamicIco.png} /><span><b>{i18n.t('common.dynamic')}</b></span></div> } <Table columns={columns} dataSource={data} bordered={true} pagination={false} size="small" ref="box" rowClassName={(v,k) =>{ return 'lottery' + k }} /> </div> ) } } // <div className={classes.lotteryTable}> // <div className={classes.lotteryTitle}> // <div>Address</div> // <div>Amount</div> // <div>Time</div> // </div> // <div className={classes.lotterybody} id="listScroll"> // // { // // list ? // // list : // // null // // } // </div> // </div> export default Lottery; const mapActionCreators = { getBtcWebsocket, btcWebsocket } const mapStateToProps = (state)=> ({ lottery : state.lottery, }) export default connect(mapStateToProps, mapActionCreators)(Lottery)
src/components/views/globals/NewVersionBar.js
aperezdc/matrix-react-sdk
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; import React from 'react'; import sdk from '../../../index'; import Modal from '../../../Modal'; import PlatformPeg from '../../../PlatformPeg'; import { _t } from '../../../languageHandler'; /** * Check a version string is compatible with the Changelog * dialog ([vectorversion]-react-[react-sdk-version]-js-[js-sdk-version]) */ function checkVersion(ver) { const parts = ver.split('-'); return parts.length == 5 && parts[1] == 'react' && parts[3] == 'js'; } export default React.createClass({ propTypes: { version: React.PropTypes.string.isRequired, newVersion: React.PropTypes.string.isRequired, releaseNotes: React.PropTypes.string, }, displayReleaseNotes: function(releaseNotes) { const QuestionDialog = sdk.getComponent('dialogs.QuestionDialog'); Modal.createTrackedDialog('Display release notes', '', QuestionDialog, { title: _t("What's New"), description: <div className="mx_MatrixToolbar_changelog">{releaseNotes}</div>, button: _t("Update"), onFinished: (update) => { if(update && PlatformPeg.get()) { PlatformPeg.get().installUpdate(); } } }); }, displayChangelog: function() { const ChangelogDialog = sdk.getComponent('dialogs.ChangelogDialog'); Modal.createTrackedDialog('Display Changelog', '', ChangelogDialog, { version: this.props.version, newVersion: this.props.newVersion, onFinished: (update) => { if(update && PlatformPeg.get()) { PlatformPeg.get().installUpdate(); } } }); }, onUpdateClicked: function() { PlatformPeg.get().installUpdate(); }, render: function() { let action_button; // If we have release notes to display, we display them. Otherwise, // we display the Changelog Dialog which takes two versions and // automatically tells you what's changed (provided the versions // are in the right format) if (this.props.releaseNotes) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.displayReleaseNotes}> { _t("What's new?") } </button> ); } else if (checkVersion(this.props.version) && checkVersion(this.props.newVersion)) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.displayChangelog}> { _t("What's new?") } </button> ); } else if (PlatformPeg.get()) { action_button = ( <button className="mx_MatrixToolbar_action" onClick={this.onUpdateClicked}> { _t("Update") } </button> ); } return ( <div className="mx_MatrixToolbar"> <img className="mx_MatrixToolbar_warning" src="img/warning.svg" width="24" height="23" alt="Warning"/> <div className="mx_MatrixToolbar_content"> {_t("A new version of Riot is available.")} </div> {action_button} </div> ); } });
frontend/components/indexComponent.js
yograterol/viperid
import React from 'react'; import { connect } from 'react-redux'; import CodeMirror from './codemirror'; import ViperidPanel from './panel'; import Head from './head'; import configureStore from '../store'; class IndexComponent extends React.Component { render() { return ( <div> <Head /> <div className="wrapper"> <CodeMirror {...this.props} /> <ViperidPanel {...this.props} /> </div> </div> ); } } function mapStateToProps(state) { const { currentSourceCode, compileCode } = state; let { isCompiling, result, error } = compileCode || { isCompiling: false, result: {} }; if (!currentSourceCode) { isCompiling = false; } return { currentSourceCode, result, isCompiling, error }; } export default connect(mapStateToProps)(IndexComponent);
app/javascript/mastodon/features/compose/components/poll_button.js
yukimochi/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ add_poll: { id: 'poll_button.add_poll', defaultMessage: 'Add a poll' }, remove_poll: { id: 'poll_button.remove_poll', defaultMessage: 'Remove poll' }, }); const iconStyle = { height: null, lineHeight: '27px', }; export default @injectIntl class PollButton extends React.PureComponent { static propTypes = { disabled: PropTypes.bool, unavailable: PropTypes.bool, active: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleClick = () => { this.props.onClick(); } render () { const { intl, active, unavailable, disabled } = this.props; if (unavailable) { return null; } return ( <div className='compose-form__poll-button'> <IconButton icon='tasks' title={intl.formatMessage(active ? messages.remove_poll : messages.add_poll)} disabled={disabled} onClick={this.handleClick} className={`compose-form__poll-button-icon ${active ? 'active' : ''}`} size={18} inverted style={iconStyle} /> </div> ); } }
app/components/FormInput/index.js
JSSolutions/Perfi
import React from 'react'; import T from 'prop-types'; import { ViewPropTypes } from 'react-native'; import Input from '../Input'; import TouchableItem from '../TouchableItem'; import Text from '../Text'; import s from './styles'; import { colors, dimensions } from '../../styles'; const renderIcon = (icon) => { if (icon.name) { return { ...icon, size: dimensions.iconSize, }; } return null; }; const FormInput = (props) => { const { isDropped, onPress, value, placeholder, disabledPlaceholder, style, containerStyle, isSelected, icon, label, labelStyle, disabled = false, } = props; return ( <TouchableItem onPress={onPress} style={containerStyle}> {!!label && <Text style={[s.label, labelStyle]}>{label}</Text>} <Input editable={false} containerStyle={style} secondContainerStyle={[s.secondInputContainer, disabled && { backgroundColor: colors.grey, }, isSelected && s.selectedSecondInputContainer]} style={[s.inputStyle, isSelected && s.selectedInputStile]} isValid icon={renderIcon(icon, isDropped)} iconRight={{ name: isDropped ? 'chevron-up' : 'chevron-down', size: dimensions.iconSize - 4, color: isSelected ? colors.green : colors.grey, }} leftIconStyle={s.leftIconStyle} rightIconStyle={s.rightIconStyle} multiline={false} pointerEvents="none" value={value} placeholder={disabled ? disabledPlaceholder : placeholder} placeholderColor={disabled ? colors.green : null} /> </TouchableItem> ); }; FormInput.propTypes = { isDropped: T.bool, onPress: T.func, placeholder: T.string, disabledPlaceholder: T.string, style: ViewPropTypes.style, containerStyle: ViewPropTypes.style, value: T.string, isSelected: T.any, icon: T.object, label: T.string, labelStyle: Text.propTypes.style, disabled: T.bool, }; export default FormInput;
_theme/template/Articles.js
ElemeFE/react-amap
import React from 'react'; import Layout from './Layout'; import SideMenu from './Menu/SideMenu'; import PureArticle from './Content/PureArticle'; export default function Article(props) { const pageData = props.pageData; return <Layout route={props.route}> <div id="doc"> <aside id="aside"> <SideMenu type="articles" defaultSelectedKey={props.routeParams.doc} data={props.data} /> </aside> <article id="article" className="pure-article"> <PureArticle pageData={pageData} utils={props.utils}/> </article> </div> </Layout>; }
src/containers/App.js
ashmaroli/jekyll-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { HotKeys } from 'react-hotkeys'; import DocumentTitle from 'react-document-title'; import { fetchConfig } from '../ducks/config'; import { fetchMeta } from '../ducks/dashboard'; import keyboardShortcuts from '../constants/keyboardShortcuts'; // Components import Sidebar from './Sidebar'; import Header from './Header'; import Notifications from './Notifications'; class App extends Component { componentDidMount() { const { fetchConfig, fetchMeta } = this.props; fetchConfig(); fetchMeta(); } componentWillReceiveProps(nextProps) { if (this.props.updated !== nextProps.updated) { const { fetchConfig } = this.props; fetchConfig(); } } render() { const { isFetching } = this.props; if (isFetching) { return null; } const config = this.props.config.content; const { admin, site } = this.props.meta; return ( <DocumentTitle title="Jekyll Manager"> <HotKeys keyMap={keyboardShortcuts} className="wrapper"> { config && <div> {site && <Sidebar config={config} site={site} />} <div className="container"> {admin && <Header config={config} admin={admin} />} <div className="content"> {this.props.children} </div> </div> <Notifications /> </div> } </HotKeys> </DocumentTitle> ); } } App.propTypes = { children: PropTypes.element, fetchConfig: PropTypes.func.isRequired, fetchMeta: PropTypes.func.isRequired, config: PropTypes.object.isRequired, meta: PropTypes.object.isRequired, isFetching: PropTypes.bool.isRequired, updated: PropTypes.bool }; const mapStateToProps = (state) => ({ config: state.config.config, meta: state.dashboard.meta, updated: state.config.updated, isFetching: state.config.isFetching, }); const mapDispatchToProps = (dispatch) => bindActionCreators({ fetchConfig, fetchMeta }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(App);
src/svg-icons/social/share.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialShare = (props) => ( <SvgIcon {...props}> <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/> </SvgIcon> ); SocialShare = pure(SocialShare); SocialShare.displayName = 'SocialShare'; SocialShare.muiName = 'SvgIcon'; export default SocialShare;
views/decoration_toggle.js
williara/black-screen
import React from 'react'; export default React.createClass({ getInitialState() { return {enabled: this.props.invocation.state.decorate}; }, handleClick(event) { stopBubblingUp(event); var newState = !this.state.enabled; this.setState({enabled: newState}); this.props.invocation.setState({decorate: newState}); }, render() { var classes = ['decoration-toggle']; if (!this.state.enabled) { classes.push('disabled'); } return ( <a href="#" className={classes.join(' ')} onClick={this.handleClick}> <i className="fa fa-magic"></i> </a> ); } });
docs/src/pages/component-demos/app-bar/ButtonAppBar.js
dsslimshaddy/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; const styles = { root: { marginTop: 30, width: '100%', }, flex: { flex: 1, }, }; function ButtonAppBar(props) { const classes = props.classes; return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton color="contrast" aria-label="Menu"> <MenuIcon /> </IconButton> <Typography type="title" color="inherit" className={classes.flex}> Title </Typography> <Button color="contrast">Login</Button> </Toolbar> </AppBar> </div> ); } ButtonAppBar.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ButtonAppBar);
app/javascript/mastodon/features/ui/components/upload_area.js
tootsuite/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { FormattedMessage } from 'react-intl'; export default class UploadArea extends React.PureComponent { static propTypes = { active: PropTypes.bool, onClose: PropTypes.func, }; handleKeyUp = (e) => { const keyCode = e.keyCode; if (this.props.active) { switch(keyCode) { case 27: e.preventDefault(); e.stopPropagation(); this.props.onClose(); break; } } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } render () { const { active } = this.props; return ( <Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}> {({ backgroundOpacity, backgroundScale }) => ( <div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}> <div className='upload-area__drop'> <div className='upload-area__background' style={{ transform: `scale(${backgroundScale})` }} /> <div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div> </div> </div> )} </Motion> ); } }
src/components/GraphControls.js
chrisfisher/graph-editor
// @flow import React from 'react'; import { connect } from 'react-redux'; import { addNode, deleteNodes, bringNodesToFront, sendNodesToBack, addManyNodes, selectAllNodes, } from '../actions'; const DEFAULT_NODE_WIDTH = 100; const DEFAULT_NODE_HEIGHT = 100; const GraphControls = props => ( <div> <span className="button" onClick={() => { props.addNode(DEFAULT_NODE_WIDTH, DEFAULT_NODE_HEIGHT); }}>Add</span> <span className="button" onClick={() => { props.addManyNodes(DEFAULT_NODE_WIDTH, DEFAULT_NODE_HEIGHT); }}>Add many</span> <span className="button" onClick={() => { props.selectAllNodes(); }}>Select all</span> <span className="button" onClick={() => { props.deleteNodes(); }}>Delete</span> <span className="button" onClick={() => { props.bringNodesToFront(); }}>Bring to front</span> <span className="button" onClick={() => { props.sendNodesToBack(); }}>Send to back</span> </div> ); export default connect( null, { addNode, deleteNodes, bringNodesToFront, sendNodesToBack, addManyNodes, selectAllNodes, } )(GraphControls);
src/svg-icons/action/search.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSearch = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/> </SvgIcon> ); ActionSearch = pure(ActionSearch); ActionSearch.displayName = 'ActionSearch'; ActionSearch.muiName = 'SvgIcon'; export default ActionSearch;
src/index.js
cindyqian/BoardGames
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware } from 'redux' import ReducerManager from './components/ReducerManager' import {logger, currentAction, asyncDispatchMiddleware, callbackMiddleware} from './components/CommonMiddleware' import cs from './services/CommunicationService' import TopContainer from './components/TopContainer' import MainRouteContainer from './components/MainRouteContainer' import StackViewContainer from './components/StackViewContainer' import { Router, Route, IndexRoute, useRouterHistory, browserHistory } from 'react-router' import { createHashHistory } from 'history' const history = useRouterHistory(createHashHistory)({ queryKey: false }); let store = createStore(ReducerManager, applyMiddleware(logger, currentAction, asyncDispatchMiddleware, callbackMiddleware)); cs.init(store); render( <Provider store={store}> <Router history={browserHistory }> <Route path='/' component={TopContainer}> <IndexRoute component={MainRouteContainer} /> <Route path='main' component={MainRouteContainer} /> </Route> <Route path='/cindyqian/BoardGames/' component={TopContainer}> <IndexRoute component={MainRouteContainer} /> <Route path='main' component={MainRouteContainer} /> </Route> </Router> </Provider>, document.getElementById('root') )
src/containers/Ecommerce/checkout/billing-form.js
EncontrAR/backoffice
import React from 'react'; import Input from '../../../components/uielements/input'; import Select from '../../../components/uielements/select'; import Checkbox from '../../../components/uielements/checkbox'; import InputBox from './input-box'; import IntlMessages from '../../../components/utility/intlMessages'; const Option = Select.Option; class BillingForm extends React.Component { handleOnChange = checkedValues => { console.log('checked = ', checkedValues); }; render() { return ( <div className="isoBillingForm"> <div className="isoInputFieldset"> <InputBox label={<IntlMessages id="checkout.billingform.firstname" />} important /> <InputBox label={<IntlMessages id="checkout.billingform.lastname" />} important /> </div> <div className="isoInputFieldset"> <InputBox label={<IntlMessages id="checkout.billingform.company" />} /> </div> <div className="isoInputFieldset"> <InputBox label={<IntlMessages id="checkout.billingform.email" />} important /> <InputBox label={<IntlMessages id="checkout.billingform.mobile" />} /> </div> <div className="isoInputFieldset"> <div className="isoInputBox"> <label> {<IntlMessages id="checkout.billingform.country" />} </label> <Select size="large" defaultValue="unitedstate"> <Option value="argentina">Argentina</Option> <Option value="australia">Australia</Option> <Option value="brazil">Brazil</Option> <Option value="france">France</Option> <Option value="germany">Germany</Option> <Option value="southafrica">South Africa</Option> <Option value="spain">Spain</Option> <Option value="unitedstate">United State</Option> <Option value="unitedkingdom">United Kingdom</Option> </Select> </div> <InputBox label={<IntlMessages id="checkout.billingform.city" />} /> </div> <div className="isoInputFieldset vertical"> <InputBox label={<IntlMessages id="checkout.billingform.address" />} placeholder="Address" /> <Input size="large" placeholder="Apartment, suite, unit etc. (optional)" style={{ marginTop: '35px' }} /> </div> <Checkbox onChange={this.handleOnChange}> <IntlMessages id="checkout.billingform.checkbox" /> </Checkbox> </div> ); } } export default BillingForm;
client/src/entwine/TinyMCE_sslink-file.js
silverstripe/silverstripe-asset-admin
/* global tinymce, editorIdentifier, ss */ import i18n from 'i18n'; import TinyMCEActionRegistrar from 'lib/TinyMCEActionRegistrar'; import React from 'react'; import ReactDOM from 'react-dom'; import jQuery from 'jquery'; import ShortcodeSerialiser from 'lib/ShortcodeSerialiser'; import InsertMediaModal from 'containers/InsertMediaModal/InsertMediaModal'; import Injector, { loadComponent } from 'lib/Injector'; import * as modalActions from 'state/modal/ModalActions'; const commandName = 'sslinkfile'; // Link to external url TinyMCEActionRegistrar.addAction( 'sslink', { text: i18n._t('AssetAdmin.LINKLABEL_FILE', 'Link to a file'), // eslint-disable-next-line no-console onclick: (activeEditor) => activeEditor.execCommand(commandName), priority: 80 }, editorIdentifier, ).addCommandWithUrlTest(commandName, /^\[file_link/); const plugin = { init(editor) { editor.addCommand(commandName, () => { const field = jQuery(`#${editor.id}`).entwine('ss'); field.openLinkFileDialog(); }); }, }; const modalId = 'insert-link__dialog-wrapper--file'; const InjectableInsertMediaModal = loadComponent(InsertMediaModal); jQuery.entwine('ss', ($) => { $('textarea.htmleditor').entwine({ openLinkFileDialog() { let dialog = $(`#${modalId}`); if (!dialog.length) { dialog = $(`<div id="${modalId}" />`); $('body').append(dialog); } dialog.addClass('insert-link__dialog-wrapper'); dialog.setElement(this); dialog.open(); }, }); /** * Assumes that $('.insert-link__dialog-wrapper').entwine({}); is defined for shared functions */ $(`.js-injector-boot #${modalId}`).entwine({ renderModal(isOpen) { // We're updating the redux store from outside react. This is a bit unusual, but it's // the best way to initialise our modal setting. const { dispatch } = Injector.reducer.store; dispatch(modalActions.initFormStack('insert-link', 'admin')); const handleHide = () => { dispatch(modalActions.reset()); this.close(); }; const handleInsert = (...args) => this.handleInsert(...args); const attrs = this.getOriginalAttributes(); const selection = tinymce.activeEditor.selection; const selectionContent = selection.getContent() || ''; const tagName = selection.getNode().tagName; const requireLinkText = tagName !== 'A' && selectionContent.trim() === ''; // create/update the react component ReactDOM.render( <InjectableInsertMediaModal isOpen={isOpen} type="insert-link" onInsert={handleInsert} onClosed={handleHide} title={false} bodyClassName="modal__dialog" className="insert-link__dialog-wrapper--internal" fileAttributes={attrs} requireLinkText={requireLinkText} />, this[0] ); }, /** * @param {Object} data - Posted data * @return {Object} */ buildAttributes(data) { const shortcode = ShortcodeSerialiser.serialise({ name: 'file_link', properties: { id: data.ID }, }, true); // Add anchor const anchor = data.Anchor && data.Anchor.length ? `#${data.Anchor}` : ''; const href = `${shortcode}${anchor}`; return { href, target: data.TargetBlank ? '_blank' : '', title: data.Description, }; }, getOriginalAttributes() { const editor = this.getElement().getEditor(); const node = $(editor.getSelectedNode()); // Get href const hrefParts = (node.attr('href') || '').split('#'); if (!hrefParts[0]) { return {}; } // check if file is safe const shortcode = ShortcodeSerialiser.match('file_link', false, hrefParts[0]); if (!shortcode) { return {}; } return { ID: shortcode.properties.id ? parseInt(shortcode.properties.id, 10) : 0, Anchor: hrefParts[1] || '', Description: node.attr('title'), TargetBlank: !!node.attr('target'), }; }, }); }); // Adds the plugin class to the list of available TinyMCE plugins tinymce.PluginManager.add(commandName, (editor) => plugin.init(editor)); export default plugin;
packages/sandbox/pages/index.js
styled-components/styled-components
import React from 'react'; import styled, { createGlobalStyle } from 'styled-components'; import ButtonExample from '../src/Button.example'; const GlobalStyle = createGlobalStyle` body { font-size: 16px; line-height: 1.2; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-style: normal; padding: 0; margin: 0; color: rgb(46, 68, 78); -webkit-font-smoothing: subpixel-antialiased; } * { box-sizing: border-box; } `; const Body = styled.main` width: 100vw; min-width: 100vw; min-height: 100vh; background-image: linear-gradient(20deg, #e6356f, #69e7f7); padding: 30px 20px; `; const Heading = styled.div` text-align: center; `; const Title = styled.h1` @media (max-width: 40.625em) { font-size: 26px; } `; const Subtitle = styled.p``; const Content = styled.div` background: white; display: flex; align-items: center; justify-content: center; width: 100%; max-width: 860px; margin: 0 auto; margin-top: 60px; `; const Code = styled.span` white-space: pre; vertical-align: middle; font-family: monospace; display: inline-block; background-color: #1e1f27; color: #c5c8c6; padding: 0.1em 0.3em 0.15em; font-size: 0.8em; border-radius: 0.2em; `; const App = () => ( <Body> <GlobalStyle /> <Heading> <Title> Interactive sandbox for <Code>styled-components</Code> </Title> <Subtitle> Make changes to the files in <Code>./src</Code> and see them take effect in realtime! </Subtitle> </Heading> <Content> <ButtonExample /> </Content> </Body> ); export default App;
src/svg-icons/image/iso.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageIso = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14zm-2-2v-1.5h-5V17h5z"/> </SvgIcon> ); ImageIso = pure(ImageIso); ImageIso.displayName = 'ImageIso'; ImageIso.muiName = 'SvgIcon'; export default ImageIso;
src/Accordion.js
pivotal-cf/react-bootstrap
import React from 'react'; import PanelGroup from './PanelGroup'; const Accordion = React.createClass({ render() { return ( <PanelGroup {...this.props} accordion> {this.props.children} </PanelGroup> ); } }); export default Accordion;
src/ChipsCatalog.js
material-components/material-components-web-catalog
import React, { Component } from 'react'; import ComponentCatalogPanel from './ComponentCatalogPanel.js'; import {MDCChipSet} from '@material/chips/index'; import './styles/ChipsCatalog.scss'; const ChipsCatalog = () => { return ( <ComponentCatalogPanel hero={<ChipsHero />} title='Chips' description='Chips are compact elements that allow users to enter information, select a choice, filter content, or trigger an action.' designLink='https://material.io/go/design-chips' docsLink='https://material.io/components/web/catalog/chips/' sourceLink='https://github.com/material-components/material-components-web/tree/master/packages/mdc-chips' demos={<ChipsDemos />} /> ); } export class ChipsHero extends Component { constructor(props) { super(props); this.chipSet = null; } componentWillUnmount() { this.chipSet.destroy(); } renderChip(text) { return ( <div className='mdc-chip' role='row'> <div class='mdc-chip__ripple'></div> <div className='mdc-chip__text'>{text}</div> <span role='gridcell'> <span role='button' tabIndex='0' class='mdc-chip__text'>Chip Two</span> </span> </div> ); } render() { const initChipSet = chipSetEl => { if (chipSetEl) { this.chipSet = new MDCChipSet(chipSetEl); } } return ( <div className='mdc-chip-set' role='grid' ref={initChipSet}> {this.renderChip('Chip One')} {this.renderChip('Chip Two')} {this.renderChip('Chip Three')} {this.renderChip('Chip Four')} </div> ); } } class ChipsDemos extends Component { constructor(props) { super(props); this.chipSets = []; } componentWillUnmount() { this.chipSets.forEach(chipSet => chipSet.destroy()); } renderIcon(name, classes) { return ( <i className={`material-icons mdc-chip__icon mdc-chip__icon--leading ${classes}`}> {name} </i> ); } renderFilterCheckmark() { return( <div className='mdc-chip__checkmark' > <svg className='mdc-chip__checkmark-svg' viewBox='-2 -3 30 30'> <path className='mdc-chip__checkmark-path' fill='none' stroke='black' d='M1.73,12.91 8.1,19.28 22.79,4.59'/> </svg> </div> ); } // For choice and action chips renderChip(text, classes, leadingIcon) { return ( <div className={`mdc-chip ${classes}`} role='row'> {leadingIcon ? leadingIcon : ''} <span role='button' tabIndex='0' class='mdc-chip__text'>{text}</span> </div> ); } // For filter chips renderFilterChip(text, classes, leadingIcon) { return ( <div className={`mdc-chip ${classes}`} role='row'> {leadingIcon} {this.renderFilterCheckmark()} <span role='button' tabIndex='0' class='mdc-chip__text'>{text}</span> </div> ); } render() { const initChipSet = chipSetEl => chipSetEl && this.chipSets.push(new MDCChipSet(chipSetEl)); return ( <div> <h3 className='mdc-typography--subtitle1'>Choice Chips</h3> <div className='mdc-chip-set mdc-chip-set--choice' ref={initChipSet}> {this.renderChip('Extra Small')} {this.renderChip('Small')} {this.renderChip('Medium', 'mdc-chip--selected')} {this.renderChip('Large')} {this.renderChip('Extra Large')} </div> <h3 className='mdc-typography--subtitle1'>Filter Chips</h3> <h3 className='mdc-typography--body2'>No leading icon</h3> <div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}> {this.renderFilterChip('Tops', 'mdc-chip--selected')} {this.renderFilterChip('Bottoms', 'mdc-chip--selected')} {this.renderFilterChip('Shoes')} {this.renderFilterChip('Accessories')} </div> <h3 className='mdc-typography--body2'>With leading icon</h3> <div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}> {this.renderFilterChip('Alice', 'mdc-chip--selected', this.renderIcon('face', 'mdc-chip__icon--leading mdc-chip__icon--leading-hidden'))} {this.renderFilterChip('Bob', '' /* classes */, this.renderIcon('face', 'mdc-chip__icon--leading'))} {this.renderFilterChip('Charlie', '' /* classes */, this.renderIcon('face', 'mdc-chip__icon--leading'))} {this.renderFilterChip('Danielle', '' /* classes */, this.renderIcon('face', 'mdc-chip__icon--leading'))} </div> <div className='catalog-variant'> <h3 className='mdc-typography--subtitle1'>Action Chips</h3> <div className='mdc-chip-set' ref={initChipSet}> {this.renderChip('Add to calendar', '' /* classes */, this.renderIcon('event', 'mdc-chip__icon--leading'))} {this.renderChip('Bookmark', '' /* classes */, this.renderIcon('bookmark', 'mdc-chip__icon--leading'))} {this.renderChip('Set alarm', '' /* classes */, this.renderIcon('alarm', 'mdc-chip__icon--leading'))} {this.renderChip('Get directions', '' /* classes */, this.renderIcon('directions', 'mdc-chip__icon--leading'))} </div> </div> <div className='catalog-variant'> <h3 className='mdc-typography--subtitle1'>Shaped Chips</h3> <div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}> {this.renderChip('Bookcase', 'demo-chip-shaped')} {this.renderChip('TV Stand', 'demo-chip-shaped')} {this.renderChip('Sofas', 'demo-chip-shaped')} {this.renderChip('Office chairs', 'demo-chip-shaped')} </div> </div> </div> ); } } export default ChipsCatalog;
js/components/sideBar/index.js
kondoSoft/que_hacer_movil
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Content, Text, List, ListItem, Icon, Thumbnail, View } from 'native-base'; import { setIndex, resetState } from '../../actions/list'; import navigateTo from '../../actions/sideBarNav'; import myTheme from '../../themes/base-theme'; import styles from './style'; class SideBar extends Component { static propTypes = { setIndex: React.PropTypes.func, navigateTo: React.PropTypes.func, } navigateTo(route, reset) { this.props.navigateTo(route, 'home'); // if (reset) { // this.props.resetState() // } } render() { return ( <Content style={styles.sidebar} > <View style={styles.view} > <Thumbnail square style={styles.image} source={require('../../../assets/img/Menu-Imagen.png')} /> </View> <ListItem style={styles.listItem} button onPress={() => this.navigateTo('home', true)} > <Icon style={styles.icon} name="ios-home"/> <Text style={styles.text}>INICIO</Text> </ListItem> <ListItem style={styles.listItem} button onPress={() => this.navigateTo('contactus', true)} > <Icon style={styles.icon} name="ios-mail"/> <Text style={styles.text}>CONTACTANOS</Text> </ListItem> <ListItem style={styles.listItem} button onPress={() => this.navigateTo('bookmarks', true)} > <Icon style={styles.icon} name="ios-heart"/> <Text style={styles.text}>FAVORITOS</Text> </ListItem> </Content> ); } } function bindAction(dispatch) { return { setIndex: index => dispatch(setIndex(index)), navigateTo: (route, homeRoute) => dispatch(navigateTo(route, homeRoute)), resetState: () => dispatch(resetState()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(SideBar);
client/src/components/Home/ActivityList.js
seripap/darkwire.io
import React from 'react'; import PropTypes from 'prop-types'; import ChatInput from 'components/Chat'; import Activity from './Activity'; import T from 'components/T'; import { defer } from 'lodash'; import styles from './styles.module.scss'; const ActivityList = ({ activities, openModal }) => { const [focusChat, setFocusChat] = React.useState(false); const [scrolledToBottom, setScrolledToBottom] = React.useState(true); const messageStream = React.useRef(null); const activitiesList = React.useRef(null); React.useEffect(() => { const currentMessageStream = messageStream.current; // Update scrolledToBottom state if we scroll the activity stream const onScroll = () => { const messageStreamHeight = messageStream.current.clientHeight; const activitiesListHeight = activitiesList.current.clientHeight; const bodyRect = document.body.getBoundingClientRect(); const elemRect = activitiesList.current.getBoundingClientRect(); const offset = elemRect.top - bodyRect.top; const activitiesListYPos = offset; const newScrolledToBottom = activitiesListHeight + (activitiesListYPos - 60) <= messageStreamHeight; if (newScrolledToBottom) { if (!scrolledToBottom) { setScrolledToBottom(true); } } else if (scrolledToBottom) { setScrolledToBottom(false); } }; currentMessageStream.addEventListener('scroll', onScroll); return () => { // Unbind event if component unmounted currentMessageStream.removeEventListener('scroll', onScroll); }; }, [scrolledToBottom]); const scrollToBottomIfShould = React.useCallback(() => { if (scrolledToBottom) { messageStream.current.scrollTop = messageStream.current.scrollHeight; } }, [scrolledToBottom]); React.useEffect(() => { scrollToBottomIfShould(); // Only if activities.length bigger }, [scrollToBottomIfShould, activities]); const scrollToBottom = React.useCallback(() => { messageStream.current.scrollTop = messageStream.current.scrollHeight; setScrolledToBottom(true); }, []); const handleChatClick = () => { setFocusChat(true); defer(() => setFocusChat(false)); }; return ( <div className="main-chat"> <div onClick={handleChatClick} className="message-stream h-100" ref={messageStream} data-testid="main-div"> <ul className="plain" ref={activitiesList}> <li> <p className={styles.tos}> <button className="btn btn-link" onClick={() => openModal('About')}> {' '} <T path="agreement" /> </button> </p> </li> {activities.map((activity, index) => ( <li key={index} className={`activity-item ${activity.type}`}> <Activity activity={activity} scrollToBottom={scrollToBottomIfShould} /> </li> ))} </ul> </div> <div className="chat-container"> <ChatInput scrollToBottom={scrollToBottom} focusChat={focusChat} /> </div> </div> ); }; ActivityList.propTypes = { activities: PropTypes.array.isRequired, openModal: PropTypes.func.isRequired, }; export default ActivityList;
docs/src/app/components/pages/components/AppBar/ExampleIcon.js
kittyjumbalaya/material-components-web
import React from 'react'; import AppBar from 'material-ui/AppBar'; /** * A simple example of `AppBar` with an icon on the right. * By default, the left icon is a navigation-menu. */ const AppBarExampleIcon = () => ( <AppBar title="Title" iconClassNameRight="muidocs-icon-navigation-expand-more" /> ); export default AppBarExampleIcon;
docs/src/IntroductionPage.js
chilts/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
src/routes/dashboard/index.js
zhouchao0924/SLCOPY
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Row, Col, Card } from 'antd' import { NumberCard, Quote, Sales, Weather, RecentSales, Comments, Completed, Browser, Cpu, User } from './components' import styles from './index.less' import { color } from '../../utils' const bodyStyle = { bodyStyle: { height: 432, background: '#fff', }, } function Dashboard ({ dashboard }) { const { weather, sales, quote, numbers, recentSales, comments, completed, browser, cpu, user } = dashboard const numberCards = numbers.map((item, key) => <Col key={key} lg={6} md={12}> <NumberCard {...item} /> </Col>) return ( <Row gutter={24}> {numberCards} <Col lg={18} md={24}> <Card bordered={false} bodyStyle={{ padding: '24px 36px 24px 0', }}> <Sales data={sales} /> </Card> </Col> <Col lg={6} md={24}> <Row gutter={24}> <Col lg={24} md={12}> <Card bordered={false} className={styles.weather} bodyStyle={{ padding: 0, height: 204, background: color.blue, }}> <Weather {...weather} /> </Card> </Col> <Col lg={24} md={12}> <Card bordered={false} className={styles.quote} bodyStyle={{ padding: 0, height: 204, background: color.peach, }}> <Quote {...quote} /> </Card> </Col> </Row> </Col> <Col lg={12} md={24}> <Card bordered={false} {...bodyStyle}> <RecentSales data={recentSales} /> </Card> </Col> <Col lg={12} md={24}> <Card bordered={false} {...bodyStyle}> <Comments data={comments} /> </Card> </Col> <Col lg={24} md={24}> <Card bordered={false} bodyStyle={{ padding: '24px 36px 24px 0', }}> <Completed data={completed} /> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} {...bodyStyle}> <Browser data={browser} /> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} {...bodyStyle}> <Cpu {...cpu} /> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} bodyStyle={{ ...bodyStyle.bodyStyle, padding: 0 }}> <User {...user} /> </Card> </Col> </Row> ) } Dashboard.propTypes = { dashboard: PropTypes.object, } export default connect(({ dashboard }) => ({ dashboard }))(Dashboard)
src/js/components/icons/base/Bookmark.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-bookmark`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'bookmark'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polygon fill="none" stroke="#000" strokeWidth="2" points="5 1 5 22 12 17 19 22 19 1"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Bookmark'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/routes.js
hdngr/mantenuto
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import { App, Home, Profile, Talk, Listen, Register, Registered, Login, Rooms, NotFound, Password } from 'modules'; import { TryAuth, RequireLoggedIn, RequireNotLoggedIn } from 'modules/Auth'; const Routes = () => ( <Route path='/' component={App}> <Route component={TryAuth}> {/* <Route onEnter={tryAuth} path="/" component={App}> */} <IndexRoute component={Home} /> {/* Routes requiring login */} {/* <Route onEnter={requireLogin}> */} <Route component={RequireLoggedIn}> <Route path='profile' component={Profile} /> { Talk } { Listen } {/* <Route path="talk" component={Talk} /> <Route path="listen" component={Listen} /> */} { Rooms } {/* <Route path="rooms/:slug" component={Room} /> */} {/* <Route path="loginSuccess" component={LoginSuccess} /> */} </Route> {/* Routes disallow login */} <Route component={RequireNotLoggedIn}> { Login } { Password } { Register } <Route path='registered' component={Registered} /> </Route> {/* Catch all route */} <Route path='*' component={NotFound} status={404} /> </Route> </Route> ); export default Routes;
app/javascript/mastodon/components/status.js
pixiv/mastodon
import React from 'react'; import Immutable from 'immutable'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import AvatarOverlay from './avatar_overlay'; import RelativeTimestamp from './relative_timestamp'; import DisplayName from './display_name'; import StatusContent from './status_content'; import StatusActionBar from './status_action_bar'; import AttachmentList from './attachment_list'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { MediaGallery, Video } from '../features/ui/util/async-components'; import { HotKeys } from 'react-hotkeys'; import classNames from 'classnames'; // We use the component (and not the container) since we do not want // to use the progress bar to show download progress import Bundle from '../features/ui/components/bundle'; export default class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, pawooPushHistory: PropTypes.func, }; static propTypes = { status: ImmutablePropTypes.map, account: ImmutablePropTypes.map, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onPin: PropTypes.func, onOpenMedia: PropTypes.func, onOpenVideo: PropTypes.func, onBlock: PropTypes.func, onEmbed: PropTypes.func, onHeightChange: PropTypes.func, onToggleHidden: PropTypes.func, muted: PropTypes.bool, onPin: PropTypes.func, intersectionObserverWrapper: PropTypes.object, hidden: PropTypes.bool, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, pawooMediaScale: PropTypes.string, pawooWideMedia: PropTypes.bool, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'account', 'muted', 'hidden', ] handleClick = (e) => { if (!this.context.router) { return; } const { status } = this.props; const statusId = status.getIn(['reblog', 'id'], status.get('id')); const path = `/statuses/${statusId}`; const isApple = /Mac|iPod|iPhone|iPad/.test(navigator.platform); const pawooOtherColumn = (!isApple && e.ctrlKey) || (isApple && e.metaKey); this.context.pawooPushHistory(path, pawooOtherColumn); } handleAccountClick = (e) => { if (this.context.router && e.button === 0) { const id = e.currentTarget.getAttribute('data-id'); e.preventDefault(); const path = `/accounts/${id}`; this.context.pawooPushHistory(path); } } handleExpandedToggle = () => { this.props.onToggleHidden(this._properStatus()); }; renderLoadingMediaGallery = () => { return <div className='media_gallery' style={{ height: 132 }} />; } renderLoadingVideoPlayer = () => { return <div className='media-spoiler-video' style={{ height: 132 }} />; } handleOpenVideo = (media, startTime) => { this.props.onOpenVideo(media, startTime); } handleHotkeyReply = e => { e.preventDefault(); this.props.onReply(this._properStatus(), this.context.router.history); } handleHotkeyFavourite = () => { this.props.onFavourite(this._properStatus()); } handleHotkeyBoost = e => { this.props.onReblog(this._properStatus(), e); } handleHotkeyMention = e => { e.preventDefault(); this.props.onMention(this._properStatus().get('account'), this.context.router.history); } handleHotkeyOpen = () => { const statusId = this._properStatus().get('id'); this.context.pawooPushHistory(`/statuses/${statusId}`); } handleHotkeyOpenProfile = () => { this.context.pawooPushHistory(`/accounts/${this._properStatus().getIn(['account', 'id'])}`); } handleHotkeyMoveUp = e => { this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyMoveDown = e => { this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyToggleHidden = () => { this.props.onToggleHidden(this._properStatus()); } handleHotkeyPawooOpenOtherColumn = () => { const statusId = this._properStatus().get('id'); this.context.pawooPushHistory(`/statuses/${statusId}`, true); } _properStatus () { const { status } = this.props; if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { return status.get('reblog'); } else { return status; } } render () { let media = null; let statusAvatar, prepend; const { hidden, featured } = this.props; let { status, account, pawooMediaScale, pawooWideMedia, ...other } = this.props; if (status === null) { return null; } if (hidden) { return ( <div> {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])} {status.get('content')} </div> ); } if (featured) { prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-thumb-tack status__prepend-icon' /></div> <FormattedMessage id='status.pinned' defaultMessage='Pinned toot' /> </div> ); } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { const display_name_html = { __html: status.getIn(['account', 'display_name_html']) }; prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div> <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} /> </div> ); account = status.get('account'); status = status.get('reblog'); } let attachments = status.get('media_attachments'); if (attachments.size === 0 && status.getIn(['pixiv_cards'], Immutable.List()).size > 0) { attachments = status.get('pixiv_cards').map(card => { return Immutable.fromJS({ id: Math.random().toString(), preview_url: card.get('image_url'), remote_url: '', text_url: card.get('url'), type: 'image', url: card.get('image_url'), }); }); } if (attachments.size > 0) { if (this.props.muted || attachments.some(item => item.get('type') === 'unknown')) { media = ( <AttachmentList compact media={attachments} /> ); } else if (attachments.getIn([0, 'type']) === 'video') { const video = attachments.first(); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={video.get('preview_url')} src={video.get('url')} height={229} inline sensitive={status.get('sensitive')} onOpenVideo={this.handleOpenVideo} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}> {Component => <Component media={attachments} sensitive={status.get('sensitive')} onOpenMedia={this.props.onOpenMedia} pawooOnClick={this.handleClick} pawooScale={pawooMediaScale} pawooWide={pawooWideMedia} />} </Bundle> ); } } if (account === undefined || account === null) { statusAvatar = <Avatar account={status.get('account')} size={48} />; }else{ statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />; } const handlers = this.props.muted ? {} : { reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, open: this.handleHotkeyOpen, openProfile: this.handleHotkeyOpenProfile, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleHotkeyToggleHidden, pawooOpenOtherColumn: this.handleHotkeyPawooOpenOtherColumn, }; return ( <HotKeys handlers={handlers}> <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null}> {prepend} <div className={classNames('status', `status-${status.get('visibility')}`, { muted: this.props.muted })} data-id={status.get('id')}> <div className='status__info'> <a href={status.get('url')} className='status__time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a> <a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name'> <div className='status__avatar'> {statusAvatar} </div> <DisplayName account={status.get('account')} /> </a> </div> <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} /> {media} <StatusActionBar status={status} account={account} {...other} /> </div> </div> </HotKeys> ); } }
src/docs/examples/Promotion/ExamplePromotion.js
undefinedist/sicario
import React from 'react' import Promotion from 'sicario/Promotion' /** With a custom message: */ export default function ExamplePromotion() { return ( <div> {promotions.map((props, index) => ( <Promotion {...props} {...promotionAttr} key={`promotion-${index}`} index={index} /> ))} </div> ) } const promotionAttr = { title: { titleSizes: [8], titleColor: '#ea9a4c', bold: 'normal', titlePbs: [1], }, description: { descriptionSizes: [2], descriptionColor: 'black', bold: 'normal', descriptionPbs: [1], }, } const promotions = [ { image: 'http://via.placeholder.com/400x300', titleText: 'RUN\nAND FLY', descriptionText: '가파르지 않은 경사면을 조금 뛰어 내려가면 글라이더에 공기가 차며 여러분과 파일럿을 가볍게 공중으로 띄워줍니다. 착륙 바로 전, 꼿꼿한 자세를 취하게 되며 곧 부드럽게 발을 디디게 됩니다. 비행이 종료되는 착륙장은 인터라켄의 중앙 잔디 밭 입니다.', }, { image: 'http://via.placeholder.com/400x300', titleText: 'SAFE\nTHRILLER', descriptionText: '스카이윙즈의 모든 파일럿들은 SHPA(스위스 행글라이딩, 패러글라이딩 협회)에서 공식적으로 검증 받았으며 고난이도의 훈련을 통과하였습니다. 다년간의 비행 경험을 통한 노하우와 비행스킬로 정평나있습니다. 이는 자사의 안전성과 전문성이 최상위의 평가를 받는 이유입니다.', }, ]
src/components/auth/signup.js
camboio/ibis
import React from 'react'; import { reduxForm } from 'redux-form'; import * as actions from '../../actions'; class Signup extends React.Component { handleFormSubmit(formProps){ this.props.signupUser(formProps); } renderAlert(){ if(this.props.errorMessage){ return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } } render(){ const { handleSubmit, fields: { email, password, passwordConfirm } } = this.props; return( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <label>Email:</label> <input {...email} className="form-control" /> { email.touched && email.error && <div className="error">{email.error}</div>} </fieldset> <fieldset className="form-group"> <label>Password:</label> <input {...password} type="password" className="form-control" /> { password.touched && password.error && <div className="error">{password.error}</div>} </fieldset> <fieldset className="form-group"> <label>Confirm Password:</label> <input {...passwordConfirm} type="password" className="form-control" /> { passwordConfirm.touched && passwordConfirm.error && <div className="error">{passwordConfirm.error}</div>} </fieldset> { this.renderAlert() } <button action="submit" className="btn btn-primary">Sign Up</button> </form> ); } } function mapStateToProps(state){ return { errorMessage: state.auth.error }; } function validate(formProps){ const errors = {}; errors.email = (!formProps.email) ? 'Please enter an email' : ''; errors.password = (!formProps.password) ? 'Please enter a password' : ''; errors.passwordConfirm = (!formProps.passwordConfirm) ? 'Please confirm password' : ''; if(formProps.password !== formProps.passwordConfirm){ errors.password = 'Passwords must match'; } return errors; } export default reduxForm({ form: 'signup', fields: ['email', 'password', 'passwordConfirm'], validate }, mapStateToProps, actions)(Signup);
react/features/base/react/components/web/Text.js
bgrozev/jitsi-meet
import React, { Component } from 'react'; /** * Implements a React/Web {@link Component} for displaying text similar to React * Native's {@code Text} in order to faciliate cross-platform source code. * * @extends Component */ export default class Text extends Component { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return React.createElement('span', this.props); } }
React.WebPack.Init/src/main.js
yodfz/JS
// 核心 import React from 'react'; import ReactDom from 'react-dom'; // UI import HelloWorld from './components/HelloWorld'; // class App extends React.Component { // render() { // return (<h1>hello world</h1>); // }; // } // const App = () => <h1>hello world,const!</h1>; // export default helloworld; console.log(HelloWorld); console.log(React); ReactDom.render(<HelloWorld />, window.document.querySelector('app'));
packages/veritone-react-common/src/components/DelayedProgress/index.js
veritone/veritone-sdk
// https://material-ui.com/demos/progress/#delaying-appearance // when props.loading is set to true, will delay for props.delay ms before // showing a loading indicator. import React from 'react'; import { number, bool, objectOf, any } from 'prop-types'; import Fade from '@material-ui/core/Fade'; import CircularProgress from '@material-ui/core/CircularProgress'; export default class DelayedProgress extends React.Component { static propTypes = { loading: bool, delay: number, circularProgressProps: objectOf(any) }; static defaultProps = { delay: 800, loading: false }; render() { return ( <Fade in={this.props.loading} style={{ transitionDelay: this.props.loading ? `${this.props.delay}ms` : '0ms' }} unmountOnExit > <CircularProgress {...this.props.circularProgressProps} /> </Fade> ); } }
src/frontend/src/components/LegislatorList.js
open-austin/influence-texas
import React from 'react' import PaginatedList from 'components/PaginatedList' import { ImageSquare } from 'styles' import { capitalize } from 'utils' import Typography from '@material-ui/core/Typography' const PARTIES = { R: 'Republican', D: 'Democrat', I: 'Independent', } export default function LegislatorsList({ data, nestedUnder = 'legislators', ...props }) { return ( <PaginatedList {...props} url="legislators/legislator" data={data} emptyState={<div>No legislators found</div>} nestedUnder={nestedUnder} columns={[ { render: (rowData) => ( <div style={{ display: 'flex' }}> <ImageSquare photoUrl={rowData.node.photoUrl} /> <div style={{ margin: '0 1em' }}> <Typography>{rowData.node.name}</Typography> <Typography variant="subtitle2"> {capitalize(rowData.node.chamber)} </Typography> <Typography variant="subtitle2"> {PARTIES[rowData.node.party] || rowData.node.party} </Typography> </div> </div> ), }, { field: 'node.party', render: (rowData) => ( <div style={{ textAlign: 'right' }}> District {rowData.node.district} </div> ), }, ]} /> ) }
src/components/layer/layer.js
miaoji/guojibackend
import { Modal, message } from 'antd' import React from 'react' import ReactDOM from 'react-dom' import classnames from 'classnames' import styles from './layer.less' const { info, success, error, warning, confirm } = Modal const layer = { prefixCls: 'ant-layer', index: 1, info, success, error, warning, confirm, } layer.close = (index) => new Promise((resolve, reject) => { const { prefixCls } = layer let div = document.getElementById(`${prefixCls}-reference-${index}`) if (index === undefined) { const references = document.querySelectorAll(`.${prefixCls}-reference`) div = references[references.length - 1] } if (!div) { message.error('关闭失败,未找到Dom') return } const unmountResult = ReactDOM.unmountComponentAtNode(div) if (unmountResult && div.parentNode) { div.parentNode.removeChild(div) resolve(index) } else { reject(index) } }) layer.closeAll = () => { const { prefixCls } = layer const references = document.querySelectorAll(`.${prefixCls}-reference`) let i = 0 while (i < references.length) { layer.close() i++ } } layer.open = (config) => { const props = Object.assign({}, config) const { content, ...modalProps } = props const { className, wrapClassName = '', verticalCenter = true } = modalProps const { prefixCls } = layer const index = layer.index++ let div = document.createElement('div') div.id = `${prefixCls}-reference-${index}` div.className = `${prefixCls}-reference` document.body.appendChild(div) ReactDOM.render( <Modal visible title="Title" transitionName="zoom" maskTransitionName="fade" onCancel={() => { layer.close(index) }} onOk={() => { layer.close(index) }} {...modalProps} wrapClassName={classnames({ [styles.verticalCenter]: verticalCenter, [wrapClassName]: true })} className={classnames(prefixCls, className, [`${prefixCls}-${index}`])} > <div className={`${prefixCls}-body-wrapper`} style={{ maxHeight: document.body.clientHeight - 256 }}> {content} </div> </Modal>, div) return index } export default layer
js/__tests__/helper.js
erik-sn/webapp
import chai from 'chai'; // eslint-disable-line no-unused-vars import { JSDOM } from 'jsdom'; import React from 'react'; import { Provider } from 'react-redux'; import { applyMiddleware, createStore } from 'redux'; import reducers from '../src/reducers/root_reducer'; // jsdom configuration const jsdom = new JSDOM('<!doctype html><html><body></body></html>'); const window = jsdom.window; global.window = window; global.document = window.document; global.navigator = { userAgent: 'node.js' }; global.HTMLElement = global.window.HTMLElement; // necessary for promise resolution const createStoreWithMiddleware = applyMiddleware()(createStore); export const store = createStoreWithMiddleware(reducers); export function reduxWrap(component) { return ( <Provider store={store}> {component} </Provider> ); }
src/widgets/ReactApp/index.js
cncjs/cncjs-widget-boilerplate
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; export default () => { ReactDOM.render( <App />, document.getElementById('viewport') ); };
recipe-server/client/control/components/NoMatch.js
Osmose/normandy
import React from 'react'; import { Link } from 'react-router'; /** * 404-ish view shown for routes that don't match any valid route. */ export default function NoMatch() { return ( <div className="no-match fluid-8"> <h2>Page Not Found</h2> <p>Sorry, we could not find the page you're looking for.</p> <p><Link to="/control/">Click here to return to the control index.</Link></p> </div> ); }
src/components/MainHeader/GenericDropdown.js
falmar/react-adm-lte
import React from 'react' import PropTypes from 'prop-types' import Link from '../../utils/Link' import Dropdown from './Dropdown' import DropdownToggle from './DropdownToggle' import DropdownMenu from './DropdownMenu' const GenericDropdown = (props) => { const {className, open, onToggle, children} = props const {iconClass, labelClass, label} = props const {header, footer, onClickFooter} = props return ( <Dropdown className={className} open={open} onToggle={onToggle}> <DropdownToggle onToggle={onToggle}> <i className={iconClass} /> <span className={labelClass}>{label}</span> </DropdownToggle> <DropdownMenu> <li className='header'>{header}</li> <li> <ul className='menu'> {children} </ul> </li> <li className='footer'> <Link onClick={onClickFooter}>{footer}</Link> </li> </DropdownMenu> </Dropdown> ) } GenericDropdown.propTypes = { className: PropTypes.string, open: PropTypes.bool, iconClass: PropTypes.string, labelClass: PropTypes.string, label: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]), onToggle: PropTypes.func, header: PropTypes.string, footer: PropTypes.string, onClickFooter: PropTypes.func, children: PropTypes.node } export default GenericDropdown
app/javascript/mastodon/features/home_timeline/components/column_settings.js
tateisu/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { settings, onChange } = this.props; return ( <div> <span className='column-settings__section'><FormattedMessage id='home.column_settings.basic' defaultMessage='Basic' /></span> <div className='column-settings__row'> <SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_reblogs' defaultMessage='Show boosts' />} /> </div> <div className='column-settings__row'> <SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reply']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_replies' defaultMessage='Show replies' />} /> </div> </div> ); } }
src/components/FuelSavingsResults.js
redsheep-io/redsheep.io
import React from 'react'; import PropTypes from 'prop-types'; import NumberFormatter from '../utils/numberFormatter'; // This is a stateless functional component. (Also known as pure or dumb component) // More info: https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#stateless-functional-components // And https://medium.com/@joshblack/stateless-components-in-react-0-14-f9798f8b992d // Props are being destructured below to extract the savings object to shorten calls within component. const FuelSavingsResults = ({savings}) => { // console.log(savings); // console.log("typeof", typeof(savings.monthly)); const savingsExist = NumberFormatter.scrubFormatting(savings.monthly) > 0; const savingsClass = savingsExist ? 'savings' : 'loss'; const resultLabel = savingsExist ? 'Savings' : 'Loss'; // You can even exclude the return statement below if the entire component is // composed within the parentheses. Return is necessary here because some // variables are set above. return ( <table> <tbody> <tr> <td className="fuel-savings-label">{resultLabel}</td> <td> <table> <tbody> <tr> <td>Monthly</td> <td>1 Year</td> <td>3 Year</td> </tr> <tr> <td className={savingsClass}>{savings.monthly}</td> <td className={savingsClass}>{savings.annual}</td> <td className={savingsClass}>{savings.threeYear}</td> </tr> </tbody> </table> </td> </tr> </tbody> </table> ); }; // Note that this odd style is utilized for propType validation for now. Must be defined *after* // the component is defined, which is why it's separate and down here. FuelSavingsResults.propTypes = { savings: PropTypes.object.isRequired }; export default FuelSavingsResults;
app/screens/MatchesValidation/index.js
mbernardeau/Road-to-Russia-2018
import React from 'react' // eslint-disable-next-line react/prefer-stateless-function export default class MatchesValidation extends React.PureComponent { render() { return <h1>Ceci sera la page de validation des matches.</h1> } }
node_modules/react-bootstrap/es/Tabs.js
mohammed52/something.pk
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import requiredForA11y from 'prop-types-extra/lib/isRequiredForA11y'; import uncontrollable from 'uncontrollable'; import Nav from './Nav'; import NavItem from './NavItem'; import UncontrolledTabContainer from './TabContainer'; import TabContent from './TabContent'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; import ValidComponentChildren from './utils/ValidComponentChildren'; var TabContainer = UncontrolledTabContainer.ControlledComponent; var propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: PropTypes.any, /** * Navigation style */ bsStyle: PropTypes.oneOf(['tabs', 'pills']), animation: PropTypes.bool, id: requiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: PropTypes.func, /** * Wait until the first "enter" transition to mount tabs (add them to the DOM) */ mountOnEnter: PropTypes.bool, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: PropTypes.bool }; var defaultProps = { bsStyle: 'tabs', animation: true, mountOnEnter: false, unmountOnExit: false }; function getDefaultActiveKey(children) { var defaultActiveKey = void 0; ValidComponentChildren.forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var Tabs = function (_React$Component) { _inherits(Tabs, _React$Component); function Tabs() { _classCallCheck(this, Tabs); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tabs.prototype.renderTab = function renderTab(child) { var _child$props = child.props, title = _child$props.title, eventKey = _child$props.eventKey, disabled = _child$props.disabled, tabClassName = _child$props.tabClassName; if (title == null) { return null; } return React.createElement( NavItem, { eventKey: eventKey, disabled: disabled, className: tabClassName }, title ); }; Tabs.prototype.render = function render() { var _props = this.props, id = _props.id, onSelect = _props.onSelect, animation = _props.animation, mountOnEnter = _props.mountOnEnter, unmountOnExit = _props.unmountOnExit, bsClass = _props.bsClass, className = _props.className, style = _props.style, children = _props.children, _props$activeKey = _props.activeKey, activeKey = _props$activeKey === undefined ? getDefaultActiveKey(children) : _props$activeKey, props = _objectWithoutProperties(_props, ['id', 'onSelect', 'animation', 'mountOnEnter', 'unmountOnExit', 'bsClass', 'className', 'style', 'children', 'activeKey']); return React.createElement( TabContainer, { id: id, activeKey: activeKey, onSelect: onSelect, className: className, style: style }, React.createElement( 'div', null, React.createElement( Nav, _extends({}, props, { role: 'tablist' }), ValidComponentChildren.map(children, this.renderTab) ), React.createElement( TabContent, { bsClass: bsClass, animation: animation, mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit }, children ) ) ); }; return Tabs; }(React.Component); Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; setBsClass('tab', Tabs); export default uncontrollable(Tabs, { activeKey: 'onSelect' });
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js
rafser01/installer_electron
import _transformLib from 'transform-lib'; const _components = { Foo: { displayName: 'Foo' } }; const _transformLib2 = _transformLib({ filename: '%FIXTURE_PATH%', components: _components, locals: [], imports: [] }); function _wrapComponent(id) { return function (Component) { return _transformLib2(Component, id); }; } import React, { Component } from 'react'; const Foo = _wrapComponent('Foo')(class Foo extends Component { render() {} });
src/svg-icons/communication/phonelink-erase.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhonelinkErase = (props) => ( <SvgIcon {...props}> <path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z"/> </SvgIcon> ); CommunicationPhonelinkErase = pure(CommunicationPhonelinkErase); CommunicationPhonelinkErase.displayName = 'CommunicationPhonelinkErase'; CommunicationPhonelinkErase.muiName = 'SvgIcon'; export default CommunicationPhonelinkErase;
src/modules/universal-discovery/components/tab-content/tab.content.panel.component.js
sunpietro/react-udw
import React from 'react'; import PropTypes from 'prop-types'; import './css/tab.content.panel.component.css'; const TabContentPanelComponent = (props) => { const attrs = { id: props.id, className: 'c-tab-content-panel' }; if (!props.isVisible) { attrs.hidden = true; } return ( <div {...attrs}> {props.children} </div> ); }; TabContentPanelComponent.propTypes = { id: PropTypes.string.isRequired, isVisible: PropTypes.bool.isRequired, children: PropTypes.any, maxHeight: PropTypes.number }; export default TabContentPanelComponent;
src/js/components/icons/base/Target.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-target`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'target'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M23,12 C23,18.075 18.075,23 12,23 C5.925,23 1,18.075 1,12 C1,5.925 5.925,1 12,1 C18.075,1 23,5.925 23,12 L23,12 Z M18,12 C18,8.691 15.309,6 12,6 C8.691,6 6,8.691 6,12 C6,15.309 8.691,18 12,18 C15.309,18 18,15.309 18,12 L18,12 Z M13,12 C13,11.448 12.552,11 12,11 C11.448,11 11,11.448 11,12 C11,12.552 11.448,13 12,13 C12.552,13 13,12.552 13,12 L13,12 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Target'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
stories/Stagger.js
unruffledBeaver/react-animation-components
import React from 'react'; import { storiesOf } from '@storybook/react'; import { withKnobs, boolean, number } from '@storybook/addon-knobs'; import { Fade, Stagger } from '../src/index'; const exampleArray = ['Example', 'Example', 'Example', 'Example', 'Example']; storiesOf('Wrappers/Stagger', module) .addDecorator(withKnobs) .add('default', () => ( <Stagger in={boolean('in', true)} reverse={boolean('reverse', false)} chunk={number('chunk', 0)} > {exampleArray.map((example, i) => ( <Fade key={`${i}-example`}> <h1>{example}</h1> </Fade> ))} </Stagger> ));
examples/03 Nesting/Drag Sources/Container.js
arnif/react-dnd
import React from 'react'; import SourceBox from './SourceBox'; import TargetBox from './TargetBox'; import Colors from './Colors'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd/modules/backends/HTML5'; @DragDropContext(HTML5Backend) export default class Container { render() { return ( <div style={{ overflow: 'hidden', clear: 'both', margin: '-.5rem' }}> <div style={{ float: 'left' }}> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW}> <SourceBox color={Colors.YELLOW} /> <SourceBox color={Colors.BLUE} /> </SourceBox> <SourceBox color={Colors.BLUE}> <SourceBox color={Colors.YELLOW} /> </SourceBox> </SourceBox> </div> <div style={{ float: 'left', marginLeft: '5rem', marginTop: '.5rem' }}> <TargetBox /> </div> </div> ); } }
src/pages/index.js
ScottDowne/donate.mozilla.org
import fs from 'fs'; import React from 'react'; import Optimizely from '../components/optimizely.js'; import OptimizelySubdomain from '../components/optimizelysubdomain.js'; import Path from 'path'; import Pontoon from '../components/pontoon.js'; var Index = React.createClass({ render: function() { var metaData = this.props.metaData; var robots = 'index, follow'; var googleFonts = "https://fonts.googleapis.com/css?family=Open+Sans:600,400,300,300italic"; if (metaData.current_url.indexOf("jan-thank-you") !== -1) { googleFonts = "https://fonts.googleapis.com/css?family=Roboto+Slab:600,400,300,200,100"; } var localesData = []; if (this.props.localesInfo.length) { this.props.localesInfo.forEach(function(locale) { if (locale === "cs") { googleFonts += "&subset=latin-ext"; } localesData.push(fs.readFileSync(Path.join(__dirname, '../../node_modules/react-intl/locale-data/' + locale.split('-')[0] + '.js'), 'utf8')); }); } if (metaData.current_url.indexOf('thank-you') !== -1) { robots = 'noindex, nofollow'; } var fileHashes = JSON.parse(fs.readFileSync(Path.join(__dirname, '../../public/webpack-assets.json'))); var ga = ` (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-49796218-32', 'auto'); ga('send', 'pageview'); `; var polyfillLocale = ""; if (this.props.locale) { polyfillLocale = '&locale=' + this.props.locale; } var dir = 'ltr'; if (['ar', 'fa', 'he', 'ur'].indexOf(this.props.locale) >= 0) { dir = 'rtl'; } return ( <html dir={dir}> <head> <meta charSet="UTF-8"/> <meta httpEquiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name='robots' content={robots}/> <meta property="og:type" content="website" /> <meta property="og:title" content={metaData.title} /> <meta property="og:site_name" content={metaData.site_name} /> <meta property="og:url" content={metaData.site_url} /> <meta property="og:description" content={metaData.desc} /> <meta property="og:image" content={metaData.facebook_image} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site" content="@mozilla" /> <meta name="twitter:title" content={metaData.title} /> <meta name="twitter:description" content={metaData.desc} /> <meta name="twitter:image" content={metaData.twitter_image} /> <link rel="preconnect" href="https://www.google-analytics.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link rel="preconnect" href="https://206878104.log.optimizely.com" /> <title>donate.mozilla.org | {metaData.site_title}</title> <OptimizelySubdomain/> <Optimizely/> <link rel="icon" href={this.props.favicon} type="image/x-icon"/> <link rel="stylesheet" href={'/' + fileHashes.main.css}/> <script dangerouslySetInnerHTML={{__html: ga}}></script> { localesData.map((localeData, index) => { return ( <script key={"localeData-" + index} dangerouslySetInnerHTML={{__html: localeData}}></script> ); }) } </head> <body> <div id="my-app" dangerouslySetInnerHTML={{__html: this.props.markup}}></div> <link rel="stylesheet" href={googleFonts}/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/> <script src={'/api/polyfill.js?features=Event,CustomEvent,Promise' + polyfillLocale}></script> <script src={'/' + fileHashes.main.js} ></script> <Pontoon/> <script src="https://checkout.stripe.com/checkout.js"></script> <script src="https://c.shpg.org/352/sp.js"></script> </body> </html> ); } }); module.exports = Index;
docs/src/app/components/pages/components/RadioButton/Page.js
ArcanisCz/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import radioButtonReadmeText from './README'; import RadioButtonExampleSimple from './ExampleSimple'; import radioButtonExampleSimpleCode from '!raw!./ExampleSimple'; import radioButtonCode from '!raw!material-ui/RadioButton/RadioButton'; import radioButtonGroupCode from '!raw!material-ui/RadioButton/RadioButtonGroup'; const description = 'The second button is selected by default using the `defaultSelected` property of ' + '`RadioButtonGroup`. The third button is disabled using the `disabled` property of `RadioButton`. The final ' + 'example uses the `labelPosition` property to position the label on the left. '; const RadioButtonPage = () => ( <div> <Title render={(previousTitle) => `Radio Button - ${previousTitle}`} /> <MarkdownElement text={radioButtonReadmeText} /> <CodeExample title="Examples" description={description} code={radioButtonExampleSimpleCode} > <RadioButtonExampleSimple /> </CodeExample> <PropTypeDescription header="### RadioButton Properties" code={radioButtonCode} /> <PropTypeDescription header="### RadioButtonGroup Properties" code={radioButtonGroupCode} /> </div> ); export default RadioButtonPage;
addons/themes/solid-state/layouts/Home.js
rendact/rendact
import $ from 'jquery' import React from 'react'; import gql from 'graphql-tag'; import {graphql} from 'react-apollo'; import moment from 'moment'; import {Link} from 'react-router'; import Menu from '../includes/Menu'; let Home = React.createClass({ componentDidMount(){ require('../assets/css/main.css') }, handleShowMenu(){ document.body.className = "is-menu-visible"; }, render(){ let { theConfig, data, thePagination, loadDone } = this.props // debugger return ( <div> <div id="page-wrapper"> {/* <header id="header" className="alt">*/} <header id="header" className=""> <h1> <strong> <Link to="/"> {theConfig ? theConfig.name : "Rendact"} </Link> </strong> </h1> <nav id="nav"> <a href="#menu" className="menuToggle" onClick={this.handleShowMenu}><span>Menu</span></a> </nav> </header> <section id="banner"> <div className="inner"> <div className="logo"><img src={ require('images/logo-128.png') } alt="" /></div> <p>{theConfig ? theConfig.tagline: "hello"}</p> </div> </section> <section id="wrapper"> <div className="wrapper"> <div className="inner"> <section className="features"> {data && data.map((post, index) => ( <article> <Link className="image" to={"/post/" + post.id}> <img src={post.imageFeatured ? post.imageFeatured.blobUrl: require('images/logo-128.png') } alt="" /> </Link> <h3> <Link className="major" to={"/post/" + post.id}>{post.title && post.title}</Link> </h3> <p dangerouslySetInnerHTML={{__html: post.content ? post.content.slice(0, 150):""}} /> <Link className="special" to={"/post/" + post.id}>Continue Reading</Link> </article> ))} </section> <h4 className="major"></h4> <h2 style={{textAlign: "center"}}> {this.props.thePagination} </h2> </div> </div> {/* {data && data.map((post, index) => ( <section id="one" className={index%2===0 ? "wrapper spotlight style1":"wrapper alt spotlight style2" }> <div className="inner"> <Link className="image" to={"/post/" + post.id}> <img src={post.imageFeatured ? post.imageFeatured.blobUrl: require('images/logo-128.png') } alt="" /> </Link> <div className="content"> <h2> <Link className="major" to={"/post/" + post.id}>{post.title && post.title}</Link> </h2> <p dangerouslySetInnerHTML={{__html: post.content ? post.content.slice(0, 200):""}} /> <Link className="special" to={"/post/" + post.id}>Continue Reading</Link> </div> </div> </section> ))} */} </section> <section id="footer"> <div className="inner"> <h2 className="major"></h2> <div className="row"> {this.props.footerWidgets.map((fw, i) => ( <div className="4u 12u$(medium)" key={i}>{fw}</div> ))} </div> <ul className="copyright"> <li>&copy; Story based theme</li><li>html5up</li><li>converted by Rendact Team</li> </ul> </div> </section> </div> <Menu {...this.props}/> </div> ) } }); export default Home;
src/renderer/controllers/preferences.js
marcus-sa/Venobo
import {ipcRenderer} from 'electron' import React from 'react' import {dispatch} from '../lib/dispatcher' import PreferencesPage from '../pages/preferences' // Controls the Preferences page export default class PreferencesController extends React.Component { constructor(props) { super(props) this.state = { isMounted: false } } componentWillMount() { const {state, props} = this if (state.isMounted) return // initialize preferences props.state.window.title = 'Preferences' props.state.unsaved = Object.assign(props.state.unsaved || {}, { prefs: Object.assign({}, props.state.saved.prefs) }) ipcRenderer.send('setAllowNav', false) callback(null) this.setState({ isMounted: true }) } componentWillUnmount() { console.log('Preferences controller unmounted') ipcRenderer.send('setAllowNav', true) this.save() } render() { return (<PreferencesPage {...this.props} />) } // Updates a single property in the UNSAVED prefs // For example: updatePreferences('foo.bar', 'baz') // Call save() to save to config.json update(property, value) { const path = property.split('.') let obj = this.props.state.unsaved.prefs for (let i = 0; i < path.length - 1; i++) { if (typeof obj[path[i]] === 'undefined') { obj[path[i]] = {} } obj = obj[path[i]] } obj[path[i]] = value } // All unsaved prefs take effect atomically, and are saved to config.json save() { const {unsaved, saved} = this.props.state if (unsaved.prefs.isFileHandler !== saved.prefs.isFileHandler) { ipcRenderer.send('setDefaultFileHandler', unsaved.prefs.isFileHandler) } if (unsaved.prefs.startup !== saved.prefs.startup) { ipcRenderer.send('setStartup', unsaved.prefs.startup) } saved.prefs = Object.assign(saved.prefs || {}, unsaved.prefs) dispatch('stateSaveImmediate') dispatch('checkDownloadPath') } }
components/base/TopNavigation/TopNavigation.js
CarbonStack/carbonstack
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { actions as sessionActions } from '../../../lib/redux/modules/session' import NewButton from './NewButton' import LogoLink from './LogoLink' import Profile from './Profile' import SignInButton from './SignInButton' class TopNavigation extends React.PureComponent { onSignInViaGithubButtonClick = () => { this.props.actions.requestSignIn('github') } onSignOutButtonClick = () => { this.props.actions.requestSignOut() } renderLeft () { const { route } = this.props switch (route.pathname) { case '/issues/show': case '/issues/new': case '/issues/edit': return ( <div className='left'> <LogoLink href={{ pathname: '/groups/show', query: { groupUniqueName: route.query.groupUniqueName } }} as={`/g/${route.query.groupUniqueName}`} > /g/{route.query.groupUniqueName} </LogoLink> </div> ) } return ( <div className='left'> <LogoLink href='/'> Carbon Stack </LogoLink> </div> ) } render () { const { route, session } = this.props return <nav> <div className='container'> {this.renderLeft()} <div className='right'> {(route.pathname === '/groups/show' || route.pathname === '/issues') && <NewButton route={route} /> } {this.props.session.user == null || <Profile user={this.props.session.user} onSignOutButtonClick={this.onSignOutButtonClick} /> } {this.props.session.user == null && <SignInButton onClick={this.onSignInViaGithubButtonClick} isSigningIn={session.isSigningIn} /> } </div> </div> <style jsx>{` nav { position: fixed; top: 0; left: 0; right: 0; z-index: 10; background-color: rgba(255,255,255,0.8); height: 50px; width: 100%; } .container { display: flex; justify-content: space-between; } .right { display: flex; } `}</style> </nav> } } const mapStateToProps = ({session, route}) => { return { session, route } } const mapDispatchToProps = dispatch => { return { actions: bindActionCreators(sessionActions, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(TopNavigation)
app/components/Contact.js
leckman/chapterbot
import React from 'react'; import { connect } from 'react-redux' import { submitContactForm } from '../actions/contact'; import Messages from './Messages'; class Contact extends React.Component { constructor(props) { super(props); this.state = { name: '', email: '', message: '' }; } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } handleSubmit(event) { event.preventDefault(); this.props.dispatch(submitContactForm(this.state.name, this.state.email, this.state.message)); } render() { return ( <div className="container"> <div className="panel"> <div className="panel-heading"> <h3 className="panel-title">Contact Form</h3> </div> <div className="panel-body"> <Messages messages={this.props.messages}/> <form onSubmit={this.handleSubmit.bind(this)} className="form-horizontal"> <div className="form-group"> <label htmlFor="name" className="col-sm-2">Name</label> <div className="col-sm-8"> <input type="text" name="name" id="name" className="form-control" value={this.state.name} onChange={this.handleChange.bind(this)} autoFocus/> </div> </div> <div className="form-group"> <label htmlFor="email" className="col-sm-2">Email</label> <div className="col-sm-8"> <input type="email" name="email" id="email" className="form-control" value={this.state.email} onChange={this.handleChange.bind(this)}/> </div> </div> <div className="form-group"> <label htmlFor="message" className="col-sm-2">Body</label> <div className="col-sm-8"> <textarea name="message" id="message" rows="7" className="form-control" value={this.state.message} onChange={this.handleChange.bind(this)}></textarea> </div> </div> <div className="form-group"> <div className="col-sm-offset-2 col-sm-8"> <button type="submit" className="btn btn-success">Send</button> </div> </div> </form> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { messages: state.messages }; }; export default connect(mapStateToProps)(Contact);
src/components/svg/Goose.js
JoeTheDave/onitama
import PropTypes from 'prop-types'; import React from 'react'; export const Goose = ({ fillColor }) => ( <svg width="210px" height="130px" viewBox="0 0 380 229" preserveAspectRatio="xMidYMid meet"> <g transform="translate(0, 229) scale(0.1, -0.1)" fill={fillColor} stroke="none"> <path d="M2775 2260 c-3 -5 2 -24 11 -42 14 -28 16 -53 11 -173 -3 -77 -10 -153 -15 -170 l-8 -30 -209 -26 c-142 -18 -219 -24 -240 -18 -16 5 -49 9 -72 9 -39 0 -43 -2 -43 -24 0 -14 10 -64 22 -113 21 -81 23 -110 22 -368 -1 -280 -12 -472 -39 -638 -19 -118 -9 -163 53 -245 37 -48 49 -41 61 36 24 144 32 295 38 765 3 268 6 487 7 487 1 0 82 11 180 25 99 14 185 25 193 25 9 0 6 -17 -12 -66 -33 -88 -76 -161 -153 -262 -65 -86 -102 -141 -102 -154 0 -41 171 78 251 174 27 33 58 77 69 99 11 21 24 39 29 39 5 0 69 -39 143 -86 157 -101 225 -137 244 -130 20 8 18 83 -4 126 -31 62 -118 95 -279 106 -51 4 -93 9 -93 12 0 3 14 41 32 83 37 91 13 81 253 109 274 32 317 27 335 -42 37 -136 67 -638 56 -948 -9 -249 -13 -277 -44 -298 -23 -15 -32 -15 -126 1 -55 9 -111 17 -123 17 -43 0 -23 -30 55 -82 115 -79 160 -126 168 -177 12 -77 52 -92 105 -39 44 44 78 122 96 221 21 110 22 567 3 897 -19 334 -19 380 3 413 33 51 21 70 -105 155 -52 36 -74 38 -135 17 -46 -16 -469 -82 -477 -74 -3 2 6 59 19 124 38 195 38 193 9 220 -45 42 -172 72 -189 45z" /> <path d="M1565 2200 c-3 -5 -3 -31 0 -57 8 -62 -1 -85 -88 -216 l-72 -108 -74 3 c-98 4 -104 -5 -71 -104 24 -71 25 -82 25 -353 0 -269 -1 -282 -22 -325 -12 -25 -32 -57 -44 -71 -20 -25 -20 -28 -5 -57 17 -33 61 -72 81 -72 7 0 37 11 67 25 61 28 185 55 385 85 237 34 266 28 276 -62 13 -110 -19 -369 -65 -516 l-19 -62 -39 0 c-21 0 -74 11 -117 24 -158 50 -167 38 -49 -64 93 -79 107 -98 128 -170 12 -40 16 -45 40 -43 37 2 94 47 123 97 52 91 102 300 135 573 18 145 24 173 47 205 24 36 25 39 9 63 -23 36 -107 94 -134 95 -13 0 -44 -7 -70 -15 -64 -20 -428 -67 -532 -69 l-85 -1 -3 365 -2 366 189 32 c105 17 197 29 205 26 13 -5 16 -24 16 -98 0 -98 -22 -271 -41 -324 -15 -44 -37 -53 -124 -51 -42 1 -79 -2 -83 -6 -4 -4 8 -19 27 -34 68 -52 101 -89 101 -114 0 -59 54 -59 114 0 75 75 105 166 126 383 14 142 23 174 61 201 16 11 29 26 29 34 0 32 -150 125 -201 125 -15 0 -47 -9 -73 -20 -37 -17 -199 -59 -229 -60 -4 0 51 57 123 128 87 85 130 134 130 149 0 47 -172 129 -195 93z" /> <path d="M684 2135 c-7 -16 -5 -24 21 -94 10 -29 19 -103 25 -210 5 -91 12 -212 16 -267 l7 -101 -74 -17 c-41 -9 -84 -19 -96 -22 -22 -6 -23 -4 -23 70 0 70 -2 77 -25 92 -28 18 -33 34 -11 34 26 0 106 39 112 55 9 23 -39 89 -77 108 -40 19 -69 8 -69 -28 0 -40 -39 -73 -150 -129 -65 -32 -106 -59 -108 -70 -3 -15 1 -16 35 -10 21 4 65 15 98 25 32 10 60 17 61 16 2 -1 4 -47 6 -101 l3 -99 -135 -34 c-74 -20 -139 -38 -143 -42 -4 -4 1 -18 11 -31 26 -32 96 -37 200 -12 l82 19 0 -116 0 -117 -126 -63 c-94 -48 -140 -65 -178 -68 -84 -7 -96 -11 -96 -36 0 -29 41 -89 73 -106 38 -20 65 -9 202 84 69 47 125 81 125 77 0 -34 -23 -239 -31 -284 -16 -79 -30 -90 -107 -80 -97 13 -105 -7 -27 -67 35 -26 49 -46 66 -92 31 -83 42 -90 85 -48 80 77 98 156 109 465 l7 190 47 30 c63 40 111 83 111 101 0 17 -19 13 -99 -23 -30 -13 -56 -22 -58 -20 -2 2 -1 49 3 103 l7 100 94 23 c108 25 112 24 113 -45 0 -22 9 -112 19 -200 l19 -160 -32 -33 c-17 -19 -65 -61 -108 -94 -73 -56 -96 -83 -80 -91 15 -8 70 14 152 61 l85 49 22 -101 c49 -218 114 -383 191 -486 72 -94 77 -91 117 63 14 51 34 116 45 145 20 51 26 102 13 102 -3 0 -32 -25 -64 -55 -32 -30 -64 -55 -73 -55 -31 0 -115 218 -142 372 l-17 96 85 91 c46 49 97 108 112 130 25 36 27 43 17 73 -23 71 -103 137 -115 96 -29 -97 -43 -132 -73 -181 -19 -32 -38 -56 -41 -53 -5 5 -31 262 -32 314 0 13 6 22 15 22 33 0 206 62 212 76 9 23 -17 44 -53 44 -18 0 -65 -7 -105 -15 -40 -9 -75 -13 -78 -10 -3 3 -6 135 -7 293 -3 323 5 293 -89 338 -59 28 -74 29 -81 9z" /> <path d="M941 1826 c-29 -34 41 -107 138 -146 43 -17 56 -18 68 -8 21 17 11 93 -16 122 -39 42 -165 63 -190 32z" /> <path d="M1503 1623 c-7 -3 -13 -16 -13 -31 0 -44 144 -162 168 -138 13 13 6 83 -10 108 -17 26 -120 69 -145 61z" /> <path d="M2733 1359 c-8 -8 -8 -19 3 -44 12 -29 11 -40 -2 -87 -37 -124 -132 -272 -249 -388 -70 -69 -93 -110 -62 -110 20 0 144 76 212 130 66 52 122 114 170 187 l27 43 142 -136 c192 -185 223 -211 244 -197 10 5 23 27 31 47 29 77 -28 167 -147 229 -72 37 -189 77 -228 77 -13 0 -24 2 -24 4 0 2 11 29 25 60 39 88 35 109 -27 150 -61 40 -98 52 -115 35z" /> <path d="M1557 730 c-70 -15 -187 -35 -260 -44 -72 -10 -145 -21 -162 -25 l-30 -7 28 -26 c56 -52 153 -55 407 -12 52 8 155 19 227 23 139 7 167 16 147 49 -5 9 -35 29 -65 44 -70 35 -124 35 -292 -2z" /> </g> </svg> ); Goose.propTypes = { fillColor: PropTypes.string.isRequired, }; export default Goose;
src/web/components/Footer.js
TeodorKolev/Help
import React from 'react'; import { Row, Col } from 'reactstrap'; const Footer = () => ( <footer className="mt-5"> <Row> <Col sm="12" className="text-right pt-3"> <p> Learn More on the <a target="_blank" rel="noopener noreferrer" href="https://github.com/mcnamee/react-native-starter-kit">Github Repo</a> &nbsp; | &nbsp; Written and Maintained by <a target="_blank" rel="noopener noreferrer" href="https://mcnam.ee">Matt Mcnamee</a>. </p> </Col> </Row> </footer> ); export default Footer;
src/index.js
jsk7/personal-web
/* eslint-disable import/default */ import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('app') );
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Base/Footer/Footer.js
lakmali/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react' export const Footer = () => ( <footer className="footer"> <div className="container-fluid"> <p>WSO2 APIM Publisher v3.0.0 | © 2017 <a href="http://wso2.com/" target="_blank"><i className="icon fw fw-wso2"/> Inc</a>.</p> </div> </footer> ); export default Footer
webpack/containers/Application/index.js
johnpmitsch/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { BrowserRouter as Router } from 'react-router-dom'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { orgId } from '../../services/api'; import * as actions from '../../scenes/Organizations/OrganizationActions'; import reducer from '../../scenes/Organizations/OrganizationReducer'; import Routes from './Routes'; import './overrides.scss'; const mapStateToProps = state => ({ organization: state.organization }); const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch); export const organization = reducer; class Application extends Component { componentDidMount() { this.loadData(); } loadData() { if (orgId()) { this.props.loadOrganization(); } } render() { return ( <Router> <Routes /> </Router> ); } } Application.propTypes = { loadOrganization: PropTypes.func.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(Application);
src/interface/icons/ViralContent.js
yajinni/WoWAnalyzer
import React from 'react'; // Viral Content by Edwin Prayogi M from the Noun Project const Icon = ({ ...other }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className="icon" {...other}> <g> <path d="M49.9931641,18.8754883c0.6904297,0,1.25-0.5595703,1.25-1.25V12.5c0-0.6904297-0.5595703-1.25-1.25-1.25 s-1.25,0.5595703-1.25,1.25v5.1254883C48.7431641,18.315918,49.3027344,18.8754883,49.9931641,18.8754883z" /> <path d="M32.7236328,22.5913086c0.2324219,0.4008789,0.6523438,0.625,1.0839844,0.625 c0.2119141,0,0.4267578-0.0537109,0.6240234-0.1674805c0.5976563-0.3452148,0.8027344-1.109375,0.4580078-1.7075195 l-2.5625-4.4389648c-0.3466797-0.5976563-1.109375-0.8037109-1.7080078-0.4575195 c-0.5976563,0.3452148-0.8027344,1.109375-0.4580078,1.7075195L32.7236328,22.5913086z" /> <path d="M16.8955078,32.3383789l4.4394531,2.5629883c0.1972656,0.1137695,0.4121094,0.1674805,0.6240234,0.1674805 c0.4316406,0,0.8515625-0.2241211,1.0839844-0.625c0.3447266-0.5976563,0.1396484-1.3623047-0.4580078-1.7075195 l-4.4394531-2.5629883c-0.5996094-0.3447266-1.3613281-0.1401367-1.7080078,0.4575195 C16.0927734,31.2285156,16.2978516,31.9931641,16.8955078,32.3383789z" /> <path d="M18.8759766,50.0068359c0-0.6904297-0.5595703-1.25-1.25-1.25H12.5c-0.6904297,0-1.25,0.5595703-1.25,1.25 s0.5595703,1.25,1.25,1.25h5.1259766C18.3164063,51.2568359,18.8759766,50.6972656,18.8759766,50.0068359z" /> <path d="M21.3417969,65.1103516l-4.4394531,2.5629883c-0.5976563,0.3452148-0.8027344,1.1098633-0.4580078,1.7075195 c0.2324219,0.4008789,0.6523438,0.625,1.0839844,0.625c0.2119141,0,0.4267578-0.0537109,0.6240234-0.1674805l4.4394531-2.5629883 c0.5976563-0.3452148,0.8027344-1.1098633,0.4580078-1.7075195C22.703125,64.9702148,21.9404297,64.7641602,21.3417969,65.1103516z " /> <path d="M34.4433594,76.9580078c-0.5996094-0.3457031-1.3613281-0.1396484-1.7080078,0.4575195l-2.5625,4.4389648 c-0.3447266,0.5981445-0.1396484,1.3623047,0.4580078,1.7075195c0.1972656,0.1137695,0.4121094,0.1674805,0.6240234,0.1674805 c0.4316406,0,0.8515625-0.2241211,1.0839844-0.625l2.5625-4.4389648 C35.2460938,78.0673828,35.0410156,77.3032227,34.4433594,76.9580078z" /> <path d="M50.0068359,81.1245117c-0.6904297,0-1.25,0.5595703-1.25,1.25V87.5c0,0.6904297,0.5595703,1.25,1.25,1.25 s1.25-0.5595703,1.25-1.25v-5.1254883C51.2568359,81.684082,50.6972656,81.1245117,50.0068359,81.1245117z" /> <path d="M67.2763672,77.4086914c-0.3466797-0.5976563-1.109375-0.8022461-1.7080078-0.4575195 c-0.5976563,0.3452148-0.8027344,1.109375-0.4580078,1.7075195l2.5625,4.4389648 c0.2324219,0.4008789,0.6523438,0.625,1.0839844,0.625c0.2119141,0,0.4267578-0.0537109,0.6240234-0.1674805 c0.5976563-0.3452148,0.8027344-1.109375,0.4580078-1.7075195L67.2763672,77.4086914z" /> <path d="M83.1044922,67.6616211l-4.4394531-2.5629883c-0.5986328-0.3461914-1.3613281-0.1401367-1.7080078,0.4575195 c-0.3447266,0.5976563-0.1396484,1.3623047,0.4580078,1.7075195l4.4394531,2.5629883 c0.1972656,0.1137695,0.4121094,0.1674805,0.6240234,0.1674805c0.4316406,0,0.8515625-0.2241211,1.0839844-0.625 C83.9072266,68.7714844,83.7021484,68.0068359,83.1044922,67.6616211z" /> <path d="M87.5,48.7431641h-5.1259766c-0.6904297,0-1.25,0.5595703-1.25,1.25s0.5595703,1.25,1.25,1.25H87.5 c0.6904297,0,1.25-0.5595703,1.25-1.25S88.1904297,48.7431641,87.5,48.7431641z" /> <path d="M78.0341797,35.0571289c0.2119141,0,0.4267578-0.0537109,0.6240234-0.1674805l4.4394531-2.5629883 c0.5976563-0.3452148,0.8027344-1.1098633,0.4580078-1.7075195c-0.3466797-0.5976563-1.1083984-0.8027344-1.7080078-0.4575195 l-4.4394531,2.5629883c-0.5976563,0.3452148-0.8027344,1.1098633-0.4580078,1.7075195 C77.1826172,34.8330078,77.6025391,35.0571289,78.0341797,35.0571289z" /> <path d="M65.5566406,23.0419922c0.1972656,0.1137695,0.4121094,0.1674805,0.6240234,0.1674805 c0.4316406,0,0.8515625-0.2241211,1.0839844-0.625l2.5625-4.4389648c0.3447266-0.5981445,0.1396484-1.3623047-0.4580078-1.7075195 c-0.5986328-0.3452148-1.3613281-0.1401367-1.7080078,0.4575195l-2.5625,4.4389648 C64.7539063,21.9326172,64.9589844,22.6967773,65.5566406,23.0419922z" /> <path d="M56.9118652,26.5949097c-0.1091309-0.0378418-0.2199707-0.0599365-0.335083-0.0667114 c-0.0233154-0.0013428-0.0444336-0.0135498-0.0679932-0.0135498H33.4414063c-0.6904297,0-1.25,0.5595703-1.25,1.25v44.4726563 c0,0.6904297,0.5595703,1.25,1.25,1.25h33.1123047c0.6904297,0,1.25-0.5595703,1.25-1.25V37.8183594 c0-0.0131226-0.0075684-0.0250854-0.0079346-0.038208c-0.00354-0.1530151-0.0336914-0.3015137-0.0917969-0.4432373 c-0.0002441-0.0006714-0.0003662-0.0012817-0.0006104-0.0018921c-0.0617676-0.1498413-0.1418457-0.2926025-0.2609863-0.4116821 l-8.965332-8.9575195l-1.0834961-1.0844727c-0.0028076-0.0028076-0.0068359-0.0037231-0.0096436-0.0064697 c-0.1055908-0.1044922-0.2287598-0.1800537-0.3590088-0.2398682C56.987915,26.618103,56.9504395,26.6081543,56.9118652,26.5949097z M63.5268555,36.5576172h-5.7719727v-5.7768555L63.5268555,36.5576172z M34.6914063,70.9873047V29.0146484h20.5634766v8.7929688 c0,0.6904297,0.5595703,1.25,1.25,1.25h8.7988281v31.9296875H34.6914063z" /> <path d="M51.2431641,41.1494141c0-3.9272461-3.1953125-7.1225586-7.1230469-7.1225586 c-3.9267578,0-7.1220703,3.1953125-7.1220703,7.1225586s3.1953125,7.1225586,7.1220703,7.1225586 C48.0478516,48.2719727,51.2431641,45.0766602,51.2431641,41.1494141z M39.4980469,41.1494141 c0-2.5488281,2.0732422-4.6225586,4.6220703-4.6225586s4.6230469,2.0737305,4.6230469,4.6225586 s-2.0742188,4.6225586-4.6230469,4.6225586S39.4980469,43.6982422,39.4980469,41.1494141z" /> <path d="M59.9033203,45.0673828h-7.5175781c-0.6904297,0-1.25,0.5595703-1.25,1.25s0.5595703,1.25,1.25,1.25h7.5175781 c0.6904297,0,1.25-0.5595703,1.25-1.25S60.59375,45.0673828,59.9033203,45.0673828z" /> <path d="M59.9033203,51.8012695H41.8935547c-0.6904297,0-1.25,0.5595703-1.25,1.25s0.5595703,1.25,1.25,1.25h18.0097656 c0.6904297,0,1.25-0.5595703,1.25-1.25S60.59375,51.8012695,59.9033203,51.8012695z" /> <path d="M59.9033203,56.8911133H41.8935547c-0.6904297,0-1.25,0.5595703-1.25,1.25s0.5595703,1.25,1.25,1.25h18.0097656 c0.6904297,0,1.25-0.5595703,1.25-1.25S60.59375,56.8911133,59.9033203,56.8911133z" /> <path d="M59.9033203,61.980957H41.8935547c-0.6904297,0-1.25,0.5595703-1.25,1.25s0.5595703,1.25,1.25,1.25h18.0097656 c0.6904297,0,1.25-0.5595703,1.25-1.25S60.59375,61.980957,59.9033203,61.980957z" /> </g> </svg> ); export default Icon;
src/components/Todo/Form.js
elemus/react-redux-todo-example
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Form extends Component { constructor(props) { super(props); this.state = { description: '' }; this.onInput = this.onInput.bind(this); this.onSubmit = this.onSubmit.bind(this); } onInput(e) { this.setState({ description: e.target.value }); } onSubmit(e) { e.preventDefault(); this.props.onTaskAdd(this.state.description.trim()); this.setState({ description: '' }); } render() { return ( <form onSubmit={this.onSubmit}> <div className="row"> <div className="form-group col-9"> <input type="text" className="form-control" placeholder="Do something..." value={this.state.description} onInput={this.onInput} required /> </div> <div className="col-3"> <button type="submit" className="btn btn-primary w-100">Add</button> </div> </div> </form> ); } } Form.propTypes = { onTaskAdd: PropTypes.func.isRequired, }; export default Form;
client/app/components/Input/index.js
bryanph/Geist
import _ from 'lodash' import React from 'react' import './styles.css' export function controlled(InputComponent) { /* * HOF for creating a controlled input * // TODO: should this also merge in value prop if set? - 2016-08-05 */ class ControlledInput extends React.Component { constructor(props) { super(props) this.onChange = this.onChange.bind(this) this.state = { value: props.value || '' } } // componentWillReceiveProps(nextProps) { // if (nextProps.value !== this.state.value) { // this.setState({ value: nextProps.value }) // } // } onChange(event) { event.persist() if (this.props.onChange) { this.props.onChange(event) } this.setState({value: event.target.value}) } render() { return ( <InputComponent {...this.props} value={this.state.value} onChange={this.onChange} /> ) } } return ControlledInput } export function debounced(Component, timeout=1000) { /* * HOF for creating a debounced onChange method */ class DebouncedComponent extends React.Component { constructor(props) { super(props) this.onChange = this.onChange.bind(this) this.debounced = _.debounce(props.debouncedOnChange, timeout) } cancel() { /* * Public method to cancel debounce */ this.debounced.cancel() } onChange(event) { event.persist() if (this.props.onChange) { this.props.onChange(event) } this.debounced(event) } render() { const { debouncedOnChange, ...restProps } = this.props return ( <Component {...restProps} onChange={this.onChange} /> ) } } return DebouncedComponent } const Input = (props) => <input {...props} /> export const InputText = (props) => ( <Input type='text' className={"input"} {...props} /> ) export const InputNumber = (props) => ( <Input type="number" {...props} /> ) import TextField from 'material-ui/TextField' export TextField from 'material-ui/TextField' export const ControlledTextField = controlled(TextField) export const DebouncedTextField = debounced(controlled(TextField)) export const DebouncedTextField500 = debounced(controlled(TextField), 500)
examples/search-form/modules/SearchForm.js
alexeyraspopov/react-coroutine
import React from 'react'; import Coroutine from 'react-coroutine'; import SearchAPI from './SearchAPI'; /* A coroutine becomes a React component via this wrapper. */ export default Coroutine.create(SearchForm); /* Async generator is used as a component that represents a stateful component with search results. The same rules are applicable as to functional component. The main difference comparing to plain functional component is that async generator yields particular UI state and then performs additional actions (awaitg for data) to create and yield new UI state. */ /* If you don't know what the thing is async generator, check the TC39 proposal: https://github.com/tc39/proposal-async-iteration#async-generator-functions */ async function* SearchForm({ query }) { /* Not really important. There is nothing to show if query is empty. */ if (query.length === 0) return null; /* This call does not finish the execution of the component. It just provides a state of UI and then doing another stuff. */ yield <p>Searching {query}...</p>; try { /* This piece is the same as with async functions. Some data is fetched and used with another plain functional component. */ let { results } = await SearchAPI.retrieve(query); return <SearchResults results={results} />; } catch (error) { return <ErrorMessage error={error} />; } } function SearchResults({ results }) { return results.length === 0 ? ( <p>No results</p> ) : ( <ul> {results.map((result) => ( <li key={result.package.name}> <h3 className="package-name"><a href={result.package.links.npm} target="_blank">{result.package.name}</a> <small className="package-version">({result.package.version})</small></h3> <p className="package-description">{result.package.description}</p> </li> ))} </ul> ); } function ErrorMessage({ error }) { return ( <details> <summary>Something went wrong!</summary> <p>{error.message}</p> </details> ); }
pages/showcase.js
styled-components/styled-components-website
import { withRouter } from 'next/router'; import React from 'react'; import { CSSTransition, TransitionGroup } from 'react-transition-group'; import styled, { css, keyframes } from 'styled-components'; import { sortedProjects } from '../companies-manifest'; import Footer from '../components/Footer'; import Image from '../components/Image'; import Nav from '../components/Nav'; import SeoHead from '../components/SeoHead'; import Navigation from '../components/Slider/Navigation'; import ShowcaseBody from '../components/Slider/ShowcaseBody'; import { generateShowcaseUrl } from '../components/Slider/ShowcaseLink'; import WithIsScrolled from '../components/WithIsScrolled'; import { blmGrey, blmMetal } from '../utils/colors'; import { headerFont } from '../utils/fonts'; import { mobile, phone } from '../utils/media'; const Container = styled.div` overflow-x: hidden; * { font-family: ${headerFont}; } h1, h2, h3, h4, h5, h6, p { margin-top: 0; } h1 { font-size: 2.5rem; margin-bottom: 0; ${phone(css` font-size: 2rem; `)} } h2 { font-size: 1.75rem; line-height: 1.5; ${phone(css` font-size: 1.5rem; `)} } h5 { margin-bottom: 0; font-size: 1rem; font-weight: 400; opacity: 0.6; } p { opacity: 0.6; } `; const Header = styled.header` position: relative; height: 512px; padding-top: 48px; background-color: #daa357; background: linear-gradient(20deg, ${blmGrey}, ${blmMetal}); overflow: hidden; ${mobile(css` padding-top: 92px; `)} `; const HeaderContent = styled.div` width: 100%; padding: 48px 0; display: grid; justify-content: space-between; grid-template-columns: minmax(0px, 512px) minmax(128px, 192px); grid-column-gap: 24px; color: #ffffff; ${phone(css` grid-template-columns: 1fr; `)} `; const Wrapper = styled.div` max-width: 1280px; width: 100%; margin: 0 auto; padding: 0 80px; ${phone(css` padding: 0 16px; `)} `; const InsetWrapper = styled.div` padding: 0 64px; ${mobile(css` padding: 0; `)} `; const Body = styled.div` position: relative; `; const BodyWrapper = styled.div` position: relative; top: -192px; ${mobile(css` top: -96px; `)} `; const Slide = styled(Image)` border-radius: 12px; box-shadow: 0 32px 48px rgba(0, 0, 0, 0.12); `; const getSlide = (childIndex) => keyframes` from { transform: translateX(${childIndex * 105}%); } to { transform: translateX(${-105 + 105 * childIndex}%); } `; const HeaderDecoration = styled.div` position: absolute; bottom: 0; left: 0; font-family: Avenir Next; font-size: 16rem; line-height: 16rem; font-weight: 800; color: rgba(0, 0, 0, 0.1); mix-blend-mode: overlay; pointer-events: none; animation: ${({ offset }) => getSlide(offset || 0)} 30s linear infinite; `; const NativeSelect = styled.select` border: 1px solid #ffffff; color: #ffffff; text-align-last: center; appearance: none; padding: 0 8px; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' fill='white'><path d='M7 10l5 5 5-5z'/></svg>"); background-position: 98% 50%; &::after { content: ''; height: 10px; width: 10px; border: 8px solid black; } `; const HeaderActions = styled.div` width: 100%; ${phone(css` display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 24px; `)} * { display: block; width: 100%; margin-top: 20px; } button, a, ${NativeSelect} { height: 50px; border-radius: 4px; font-family: Avenir Next; font-weight: 500; font-size: 1rem; line-height: 50px; ${phone(css` height: 40px; line-height: 40px; `)} } button, a { display: block; text-align: center; background-color: #ffffff; color: rgb(219, 112, 147); border: none; transition: 200ms; padding: 0; &:hover { background-color: #f3f3f3; } } `; function normalizeSlideIndex(arr, index, fn) { const result = fn(index); if (result > arr.length - 1) { return 0; } if (result < 0) { return arr.length - 1; } return result; } // Since objects don't allow for a sort order we have to map an array to the object function mapIndexToRoute(index) { const route = Object.keys(sortedProjects)[index]; return sortedProjects[route]; } function calculateSlides(sortOrder, route) { let currentSlideIndex = sortOrder.indexOf(route); if (currentSlideIndex === -1) { currentSlideIndex = 0; } const previousSlideIndex = normalizeSlideIndex(sortOrder, currentSlideIndex, (x) => x - 1); const nextSlideIndex = normalizeSlideIndex(sortOrder, currentSlideIndex, (x) => x + 1); return { currentSlide: mapIndexToRoute(currentSlideIndex), previousSlide: mapIndexToRoute(previousSlideIndex), nextSlide: mapIndexToRoute(nextSlideIndex), }; } class ArrowEvents extends React.Component { handleKeyDown = (event) => { const isLeft = event.keyCode === 37; const isRight = event.keyCode === 39; const { router, previousSlide, nextSlide } = this.props; if (!isLeft && !isRight) return; const { href, as } = generateShowcaseUrl(isLeft ? previousSlide : nextSlide); router.replace(href, as); return; }; componentDidMount() { document.addEventListener('keydown', this.handleKeyDown); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyDown); } render() { return null; } } const Showcase = ({ router }) => { const { item } = router.query; const { currentSlide, previousSlide, nextSlide } = calculateSlides(Object.keys(sortedProjects), item); const { title, src, owner, link, repo, description } = currentSlide; return ( <> <SeoHead title={`styled-components: Showcase ${title}`}> <meta name="robots" content="noodp" /> </SeoHead> <WithIsScrolled>{({ isScrolled }) => <Nav showSideNav={false} transparent={!isScrolled} />}</WithIsScrolled> <ArrowEvents router={router} previousSlide={previousSlide} nextSlide={nextSlide} /> <Container> <Header> <Wrapper> <InsetWrapper> <HeaderContent> <div> <h2>Awesome websites, by awesome humans beings.</h2> <h5> Styled components is used by teams all around the world to create beautiful websites, like these ones: </h5> </div> <HeaderActions> <NativeSelect name="category" id="categorySelect" value="all"> <option value="all">All</option> </NativeSelect> <a href="https://github.com/styled-components/styled-components-website/issues/new?template=company-showcase-request.md&title=Add+%5Bproject%5D+by+%5Bcompany%5D+to+showcase" target="_blank" rel="noopener noreferrer" > Share yours! </a> </HeaderActions> </HeaderContent> </InsetWrapper> </Wrapper> <HeaderDecoration>Showcase</HeaderDecoration> <HeaderDecoration offset={1}>Showcase</HeaderDecoration> <HeaderDecoration offset={2}>Showcase</HeaderDecoration> </Header> <Body> <Wrapper> <BodyWrapper> <Slide width={1920} height={1080} src={src} margin={0} renderImage={(props) => { return ( <TransitionGroup> <CSSTransition key={src} timeout={500} classNames="fade"> <img src={src} {...props} /> </CSSTransition> </TransitionGroup> ); }} /> </BodyWrapper> <Navigation prev={previousSlide} next={nextSlide} /> <BodyWrapper> <InsetWrapper> <ShowcaseBody title={title} description={description} owner={owner} link={link} repo={repo} /> </InsetWrapper> </BodyWrapper> </Wrapper> </Body> </Container> <Footer /> </> ); }; export default withRouter(Showcase);
client/src/components/post/EditPost.js
adityasharat/react-readable
import _ from 'lodash'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchAllPosts, updatePost } from '../../actions/PostActions'; import { fetchCommentForPost } from '../../actions/CommentActions'; class EditPost extends Component { componentDidMount() { this.props.fetchAllPosts(); this.props.fetchCommentForPost(this.props.match.params.postId); } editPost = (e) => { e.preventDefault(); const postId = this.props.post.id; const title = e.target.title.value; const body = e.target.body.value; if (body === "" || title === "") { alert("Both fields are mandatory"); } else { this.props.updatePost(postId, title, body ,() => this.props.history.push('/')); } } render() { const { post } = this.props; if (!post) { return (<h3 className="error">404 Post Not Found</h3>); } return ( <form className="form create-post" onSubmit={ this.editPost }> <h4>Edit post by {post.author}</h4> <div className="form-group"> <label htmlFor="title">Title</label> <input defaultValue={ post.title } type="text" className="form-control" name="title" id="title" placeholder="Enter title for the post" required/> </div> <div className="form-group"> <label htmlFor="body">Content</label> <textarea defaultValue={ post.body } type="text" className="form-control" name="body" id="body" placeholder="Enter contents for the post" rows="10" required/> </div> <div className="btn-group"> <button type="submit" className="btn btn-primary">Update</button> <Link className="btn btn-secondary" role="button" to={`/post/${post.id}`}>Cancel</Link> </div> </form> ); } } function mapStateToProps({ posts, comments }, { match }) { return { post: _.find(posts, { id: match.params.postId }), comments: comments[match.params.postId] }; } export default connect(mapStateToProps, { fetchAllPosts, updatePost, fetchCommentForPost })(EditPost);
example/App.js
ksincennes/react-native-maps
import React from 'react'; import { Platform, View, StyleSheet, TouchableOpacity, ScrollView, Text, Switch, } from 'react-native'; import { PROVIDER_GOOGLE, PROVIDER_DEFAULT } from 'react-native-maps'; import DisplayLatLng from './examples/DisplayLatLng'; import ViewsAsMarkers from './examples/ViewsAsMarkers'; import EventListener from './examples/EventListener'; import MarkerTypes from './examples/MarkerTypes'; import DraggableMarkers from './examples/DraggableMarkers'; import PolygonCreator from './examples/PolygonCreator'; import PolylineCreator from './examples/PolylineCreator'; import AnimatedViews from './examples/AnimatedViews'; import AnimatedMarkers from './examples/AnimatedMarkers'; import Callouts from './examples/Callouts'; import Overlays from './examples/Overlays'; import DefaultMarkers from './examples/DefaultMarkers'; import CustomMarkers from './examples/CustomMarkers'; import CachedMap from './examples/CachedMap'; import LoadingMap from './examples/LoadingMap'; import TakeSnapshot from './examples/TakeSnapshot'; import FitToSuppliedMarkers from './examples/FitToSuppliedMarkers'; import FitToCoordinates from './examples/FitToCoordinates'; import LiteMapView from './examples/LiteMapView'; import CustomTiles from './examples/CustomTiles'; import ZIndexMarkers from './examples/ZIndexMarkers'; import StaticMap from './examples/StaticMap'; import MapStyle from './examples/MapStyle'; const IOS = Platform.OS === 'ios'; const ANDROID = Platform.OS === 'android'; function makeExampleMapper(useGoogleMaps) { if (useGoogleMaps) { return example => [ example[0], [example[1], example[3]].filter(Boolean).join(' '), ]; } return example => example; } class App extends React.Component { constructor(props) { super(props); this.state = { Component: null, useGoogleMaps: ANDROID, }; } renderExample([Component, title]) { return ( <TouchableOpacity key={title} style={styles.button} onPress={() => this.setState({ Component })} > <Text>{title}</Text> </TouchableOpacity> ); } renderBackButton() { return ( <TouchableOpacity style={styles.back} onPress={() => this.setState({ Component: null })} > <Text style={{ fontWeight: 'bold', fontSize: 30 }}>&larr;</Text> </TouchableOpacity> ); } renderGoogleSwitch() { return ( <View> <Text>Use GoogleMaps?</Text> <Switch onValueChange={(value) => this.setState({ useGoogleMaps: value })} style={{ marginBottom: 10 }} value={this.state.useGoogleMaps} /> </View> ); } renderExamples(examples) { const { Component, useGoogleMaps, } = this.state; return ( <View style={styles.container}> {Component && <Component provider={useGoogleMaps ? PROVIDER_GOOGLE : PROVIDER_DEFAULT} />} {Component && this.renderBackButton()} {!Component && <ScrollView style={StyleSheet.absoluteFill} contentContainerStyle={styles.scrollview} showsVerticalScrollIndicator={false} > {IOS && this.renderGoogleSwitch()} {examples.map(example => this.renderExample(example))} </ScrollView> } </View> ); } render() { return this.renderExamples([ // [<component>, <component description>, <Google compatible>, <Google add'l description>] [StaticMap, 'StaticMap', true], [DisplayLatLng, 'Tracking Position', true, '(incomplete)'], [ViewsAsMarkers, 'Arbitrary Views as Markers', true], [EventListener, 'Events', true, '(incomplete)'], [MarkerTypes, 'Image Based Markers', true], [DraggableMarkers, 'Draggable Markers', true], [PolygonCreator, 'Polygon Creator', true], [PolylineCreator, 'Polyline Creator', true], [AnimatedViews, 'Animating with MapViews'], [AnimatedMarkers, 'Animated Marker Position'], [Callouts, 'Custom Callouts', true], [Overlays, 'Circles, Polygons, and Polylines', true], [DefaultMarkers, 'Default Markers', true], [CustomMarkers, 'Custom Markers', true], [TakeSnapshot, 'Take Snapshot', true, '(incomplete)'], [CachedMap, 'Cached Map'], [LoadingMap, 'Map with loading'], [FitToSuppliedMarkers, 'Focus Map On Markers', true], [FitToCoordinates, 'Fit Map To Coordinates', true], [LiteMapView, 'Android Lite MapView'], [CustomTiles, 'Custom Tiles', true], [ZIndexMarkers, 'Position Markers with Z-index', true], [MapStyle, 'Customize the style of the map', true], ] // Filter out examples that are not yet supported for Google Maps on iOS. .filter(example => ANDROID || (IOS && (example[2] || !this.state.useGoogleMaps))) .map(makeExampleMapper(IOS && this.state.useGoogleMaps)) ); } } const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, scrollview: { alignItems: 'center', paddingVertical: 40, }, button: { flex: 1, marginTop: 10, backgroundColor: 'rgba(220,220,220,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, back: { position: 'absolute', top: 20, left: 12, backgroundColor: 'rgba(255,255,255,0.4)', padding: 12, borderRadius: 20, width: 80, alignItems: 'center', justifyContent: 'center', }, }); module.exports = App;
docs/src/stories/implementations.js
rhalff/storybook
import React from 'react'; import { values } from 'lodash'; import Homepage from '../components/Homepage'; import Header from '../components/Header'; import Heading from '../components/Homepage/Heading'; import Demo from '../components/Homepage/Demo'; import Platforms from '../components/Homepage/Platforms'; import MainLinks from '../components/Homepage/MainLinks'; import Featured from '../components/Homepage/Featured'; import UsedBy from '../components/Homepage/UsedBy'; import Footer from '../components/Footer'; import Docs from '../components/Docs'; import DocsContainer from '../components/Docs/Container'; import DocsContent from '../components/Docs/Content'; import DocsNav from '../components/Docs/Nav'; import GridItem from '../components/Grid/GridItem'; import Grid from '../components/Grid/Grid'; import Examples from '../components/Grid/Examples'; import { docsData } from './data'; import users from './_users.yml'; import exampleData from './_examples.yml'; export default { 'Homepage.page': ( <Homepage featuredStorybooks={docsData.featuredStorybooks} users={values(users)} /> ), 'Homepage.header': <Header />, 'Homepage.heading': <Heading />, 'Homepage.demo': <Demo />, 'Homepage.built-for': <Platforms />, 'Homepage.main-links': <MainLinks />, 'Homepage.featured-storybooks': <Featured featuredStorybooks={docsData.featuredStorybooks} />, 'Homepage.used-by': <UsedBy users={values(users)} />, 'Homepage.footer': <Footer />, 'Docs.page': ( <Docs sections={docsData.sections} selectedItem={docsData.selectedItem} categories={docsData.categories} selectedCatId="cat-2" /> ), 'Docs.docs-container': ( <DocsContainer sections={docsData.sections} selectedItem={docsData.selectedItem} categories={docsData.categories} selectedCatId="cat-2" /> ), 'Docs.docs-content': ( <DocsContent title={docsData.selectedItem.title} content={docsData.selectedItem.content} /> ), 'Docs.docs-nav': ( <DocsNav sections={docsData.sections} selectedSection={docsData.selectedItem.sectionId} selectedItem={docsData.selectedItem.id} /> ), 'Grid.grid-item': <GridItem {...values(exampleData)[0]} />, 'Grid.grid': <Grid items={values(exampleData)} columnWidth={300} />, 'Grid.examples': <Examples items={values(exampleData)} />, };