mobx-react#Observer TypeScript Examples
The following examples show how to use
mobx-react#Observer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LanguageSwitcher.tsx From jmix-frontend with Apache License 2.0 | 7 votes |
LanguageSwitcher = observer((props: LanguageSwitcherProps) => {
const intl = useIntl();
const mainStore = useMainStore();
const handleChange = useCallback(
(locale: string) => runInAction(() => (mainStore.locale = locale)),
[mainStore]
);
if (localesStore.localesInfo.length === 1) {
return null; // Do not show LanguageSwitcher if there is only a single locale option
}
return (
<Select
defaultValue={mainStore.locale ?? undefined}
onChange={handleChange}
size="small"
style={props.style}
bordered={false}
className={props.className}
dropdownMatchSelectWidth={false}
aria-label={intl.formatMessage({ id: "a11y.select.LanguageSwitcher" })}
>
{localesStore.localesInfo.map(({ locale, caption }) => (
<Select.Option key={locale} value={locale}>
{caption}
</Select.Option>
))}
</Select>
);
})
Example #2
Source File: Forms.tsx From clarity with Apache License 2.0 | 6 votes |
TextFieldWithFormState = observer(
(props: TextFieldWithFormStateProps) => {
const { fieldState, ...otherProps } = props;
return (
<TextField
value={fieldState?.value}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
fieldState?.onChange(e.target.value);
}}
error={fieldState?.hasError}
helperText={fieldState?.error}
{...otherProps}
/>
);
}
)
Example #3
Source File: DataTable.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
dataTable = injectIntl( injectMainStore( injectMetadata( observer( DataTableComponent ) ) ) )
Example #4
Source File: Accounts.tsx From clarity with Apache License 2.0 | 6 votes |
Balance = observer(
(props: { balance: ObservableValue<AccountBalance> }) => {
const value = props.balance.value;
if (value == null) return null;
const balance =
value.balance === undefined ? 'n/a' : CSPR({ motes: value.balance });
return (
<div
className="text-right"
title={`As of block ${value.blockHashBase16}`}
>
{balance}
</div>
);
}
)
Example #5
Source File: Form.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
EnumField = observer(({enumClass, ...rest}: EnumFieldProps) => {
const metadata = useMetadata();
const mainStore = useMainStore();
const enumInfo = metadata.enums.find((enm: EnumInfo) => enm.name === enumClass);
const enumValues: EnumInfo['values']= enumInfo?.values || []
return <Select {...rest} >
{enumValues.map((enumValue) =>
<Select.Option key={enumValue.name} value={enumValue.name}>
{mainStore.enumMessages?.[enumValue.caption] || [enumValue.name]}
</Select.Option>
)}
</Select>
})
Example #6
Source File: App.tsx From clarity with Apache License 2.0 | 6 votes |
Alerts = observer((props: AppProps) => {
if (props.errors.lastError == null) return null;
// Not using the `data-dismiss="alert"` to dismiss via Bootstrap JS
// becuase then it doesn't re-render when there's a new error.
return (
<div id="alert-message">
<Alert severity="error" onClose={() => props.errors.dismissLast()}>
<AlertTitle>Error!</AlertTitle>
{props.errors.lastError}
</Alert>
</div>
);
})
Example #7
Source File: CompositionO2M.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
CompositionO2M = observer((props: CompositionComponentProps) => {
const {
value,
parentEntityName,
onChange,
screensControl,
attrInfo,
entityNamesInfo,
routingPath
} = props;
const {openViewerScreen} = screensControl;
const metadata = useMetadata();
const entityList = (value as MayHaveId[])?.map(item => ant_to_jmixFront(item, parentEntityName, metadata)) ?? [];
const handleClick = useCallback(() => {
openViewerScreen({
screensControl,
mode: ViewerModes.Inspection,
entityAttrs: getAllEntityPropertyNames(attrInfo.type, metadata),
entityNamesInfo,
routingPath,
entityList,
onEntityListChange: onChange
}, `${attrInfo.name} view`);
}, [attrInfo, entityNamesInfo, entityList, onChange, routingPath, screensControl]);
return (
<Button type='link'
onClick={handleClick}
className='jmix-composition-field jmix-composition-field-upsert-btn'
>
<BtnTitle value={value as MayHaveId[]} />
</Button>
);
})
Example #8
Source File: BlockDetails.tsx From clarity with Apache License 2.0 | 6 votes |
BlockTable = observer(
(props: {
blockHashBase16: string;
block: BlockResult | null;
refresh: () => void;
}) => {
const attrs = props.block && blockAttrs(props.block);
return (
<DataTable
title={`Block ${props.blockHashBase16}`}
headers={[]}
rows={attrs}
renderRow={(attr, i) => (
<tr key={i}>
<th>{attr[0]}</th>
<td>{attr[1]}</td>
</tr>
)}
refresh={() => props.refresh()}
/>
);
}
)
Example #9
Source File: EntityInscpectorMain.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
EntityInspectorMain = observer(({screensControl, routingPath}: Props) => {
const [entityName, setEntityName] = useState<string>();
const metadata: Metadata = useMetadata();
const onSelectChange = useCallback((value: string) => {
saveHistory(routingPath);
setEntityName(value);
}, []);
const allEntitiesNames = useMemo(() => {
return getAllPersistentEntityNames(metadata)
}, [metadata]);
const entityAttrs: string[] = useMemo(() => {
return entityName
? getAllEntityPropertyNames(entityName, metadata) ?? []
: []
}, [entityName]);
return (
<>
<EntitySelect
entities={allEntitiesNames}
onSelectChange={onSelectChange}
/>
{renderEntityDataViewer(entityName, entityAttrs,allEntitiesNames,routingPath, screensControl)}
</>
)
})
Example #10
Source File: SubmitProposal.tsx From dxvote with GNU Affero General Public License v3.0 | 6 votes |
SubmitProposalPage = observer(() => {
let match = useRouteMatch();
return (
<Switch>
<Route path={`${match.path}/custom`}>
<NewProposalPage />{' '}
</Route>
<Route path={`${match.path}/contributor`}>
<ContributorProposalPage />{' '}
</Route>
</Switch>
);
})
Example #11
Source File: ConnectedPeers.tsx From clarity with Apache License 2.0 | 6 votes |
@observer
export default class ConnectedPeers extends RefreshableComponent<Props, {}> {
async refresh() {
await this.props.connectedPeersContainer.refreshPeers();
}
render() {
const { connectedPeersContainer } = this.props;
return (
<DataTable
title="Connected Peers"
refresh={() => this.refresh()}
headers={['Node ID', 'Address']}
rows={connectedPeersContainer.peers}
renderRow={node => {
return (
<tr key={node.nodeId}>
<td>{node.nodeId}</td>
<td>{node.address} </td>
</tr>
);
}}
/>
);
}
}
Example #12
Source File: CompositionO2MField.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
CompositionO2MField = observer((props: CompositionO2MFieldProps) => {
const {value, entityName, onChange} = props;
const metadata = useMetadata();
const screens = useContext(ScreensContext);
const onOpenScreenError = useOpenScreenErrorCallback()
const entityList = value?.map(item => ant_to_jmixFront(item, entityName, metadata)) ?? [];
const handleClick = useCallback(() => {
openEntityListScreen({
entityName,
entityList,
screens,
onEntityListChange: onChange,
onOpenScreenError,
props
});
}, [entityName, entityList, screens, onChange]);
return (
<Button type='link'
onClick={handleClick}
className={classNames(
styles.compositionField,
styles.upsertBtn
)}
>
<BtnTitle value={value} />
</Button>
);
})
Example #13
Source File: NewProposalType.tsx From dxvote with GNU Affero General Public License v3.0 | 6 votes |
NewProposalTypePage = observer(() => {
const {
context: { configStore },
} = useContext();
const history = useHistory();
const [proposalTypes, setProposalTypes] = useState([]);
const options = [];
useEffect(() => {
setProposalTypes(configStore.getProposalTypes());
}, []);
proposalTypes.forEach(type => {
const path =
type.id === 'custom' ? `submit/${type.id}` : `metadata/${type.id}`;
options.push(
<ProposalType onClick={() => history.push(path)}>
{type.title}
</ProposalType>
);
});
return (
<VerticalLayout>
<NavigationBar>
<BackToProposals onClick={() => history.push('../proposals')}>
{`< Back `}
</BackToProposals>
<Title>Choose Proposal Type</Title>
<Spacer />
</NavigationBar>
<OptionsWrapper>{options}</OptionsWrapper>
</VerticalLayout>
);
})
Example #14
Source File: DeployContracts.tsx From clarity with Apache License 2.0 | 6 votes |
MapArgumentCol = observer(
(props: {
infix: string;
keyDeployArgument: FormDeployArgument;
valueDeployArgument: FormDeployArgument;
}) => {
return (
<div style={{ display: 'flex', flexGrow: 1, flexDirection: 'column' }}>
<div
style={{ alignItems: 'center', display: 'flex' }}
className={'mb-2'}
>
<span className={'ml-3 mr-2'} style={{ width: '3rem' }}>
Key:
</span>
<TypeSelectCol
supportComplexType={false}
infix={props.infix}
deployArgument={props.keyDeployArgument}
/>
</div>
<div
style={{ alignItems: 'center', display: 'flex' }}
className={'mb-2'}
>
<span className={'ml-3 mr-2'} style={{ width: '3rem' }}>
Value:
</span>
<TypeSelectCol
supportComplexType={false}
infix={props.infix}
deployArgument={props.valueDeployArgument}
/>
</div>
</div>
);
}
)
Example #15
Source File: ContentArea.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
ContentArea = observer(() => {
const {contentDisplayMode} = useMainStore();
switch (contentDisplayMode) {
case ContentDisplayMode.ActivateExistingTab:
case ContentDisplayMode.AlwaysNewTab:
return <MultiTabs />;
case ContentDisplayMode.NoTabs:
return <SingleContentArea />;
default:
assertNever('MainStore.contentDisplayMode', contentDisplayMode);
}
})
Example #16
Source File: DeployContracts.tsx From clarity with Apache License 2.0 | 6 votes |
ValueInputCol = observer(
(props: { deployArgument: FormDeployArgument }) => {
return (
<td>
<div>
<input
className={`
form-control
${
!props.deployArgument.$.value.hasBeenValidated
? ''
: props.deployArgument.$.value.hasError ||
props.deployArgument.hasFormError
? 'is-invalid'
: ''
}
`}
type="text"
value={props.deployArgument.$.value.value}
onChange={e => {
props.deployArgument.$.value.onChange(e.target.value);
}}
onBlur={() => {
props.deployArgument.enableAutoValidationAndValidate();
props.deployArgument.$.value.enableAutoValidationAndValidate();
}}
/>
{(props.deployArgument.$.value.hasError ||
props.deployArgument.hasFormError) && (
<div className="invalid-feedback">
{props.deployArgument.$.value.error ||
props.deployArgument.formError}
</div>
)}
</div>
</td>
);
}
)
Example #17
Source File: index.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
MultiTabs = observer(() => {
if (!tabs.tabs.length) {
return null;
}
return (
<Tabs activeKey={tabs.currentTab?.key} onChange={onTabChange} className={styles.tab}>
{tabs.tabs.map((item) => (
<TabPane
tab={
<Space size={10}>
<FormattedMessage id={item.title}/>
<CloseOutlined
role={"button"}
tabIndex={0}
className={classNames(styles.icon, styles.closeButton)}
onKeyDown={(e) => handleCloseKeyDown(e, item)}
onClick={(e) => handleCloseClick(e, item)}
/>
</Space>
}
key={item.key}
>
<TabContent item={item} />
</TabPane>
))}
</Tabs>
);
})
Example #18
Source File: Faucet.tsx From clarity with Apache License 2.0 | 6 votes |
@observer
class Faucet extends RefreshableComponent<Props, {}> {
refresh() {
this.props.auth.refreshAccounts();
this.props.faucet.refreshFaucetRequestStatus();
}
render() {
const { auth, faucet } = this.props;
return (
<div>
<FaucetForm auth={auth} requestTokens={x => faucet.requestTokens(x)} />
<StatusTable
requests={faucet.faucetRequests}
onRefresh={() => faucet.refreshFaucetRequestStatus()}
/>
</div>
);
}
}
Example #19
Source File: DatatypesCalendar.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
DatatypesCalendar = observer(() => {
const {
events,
executeListQuery,
listQueryResult: { loading, error },
currentMonthDayjs,
handleCalendarPaginationChange
} = useCalendar<DatatypesTestEntity>({
listQuery: SCR_DATATYPESTESTENTITY_LIST,
routingPath: ROUTING_PATH,
entityName: ENTITY_NAME,
eventStartDayPropertyName: EVENT_START_DAY_PROPERTY_NAME,
eventEndDayPropertyName: EVENT_END_DAY_PROPERTY_NAME,
eventTitlePropertyName: EVENT_TITLE_PROPERTY_NAME,
eventDescriptionPropertyName: EVENT_DESCRIPTION_PROPERTY_NAME
});
if (error != null) {
console.error(error);
return <RetryDialog onRetry={executeListQuery} />;
}
if (loading || events == null) {
return <Spinner />;
}
return (
<Card>
<Calendar
events={events}
value={currentMonthDayjs}
onPanelChange={handleCalendarPaginationChange}
/>
</Card>
);
})
Example #20
Source File: Search.tsx From clarity with Apache License 2.0 | 6 votes |
@observer
class Search extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
this.props.search.reset();
}
render() {
return (
<div>
<SearchForm container={this.props.search} />
<Results container={this.props.search} />
</div>
);
}
}
Example #21
Source File: loadingNetwork.tsx From dxvote with GNU Affero General Public License v3.0 | 6 votes |
LoadingNetworkHeader = observer(() => {
const isTestingEnv = !window?.location?.href?.includes('dxvote.eth');
return (
<NavWrapper>
<NavSection>
<>
<MenuItem>
<img alt="dxdao" src={dxdaoIcon} />
{isTestingEnv && <WarningDev>Testing Environment</WarningDev>}
</MenuItem>
</>
</NavSection>
</NavWrapper>
);
})
Example #22
Source File: Notifications.tsx From eth2stats-dashboard with MIT License | 6 votes |
Notifications = observer((props: INotificationsProps) => {
const notifStore = props.notifStore;
let items: React.ReactNode[] = [];
notifStore.list.forEach((n: INotification, key: number) => {
let bg = "bg-blue-500";
let text = "text-white";
if (n.type === "error") {
bg = "bg-red-500";
}
if (n.type === "success") {
bg = "bg-green-500";
}
if (n.type === "warn") {
bg = "bg-orange-500";
}
items.push(
<div
className={`w-full py-2 px-4 h-auto flex animated faster ${n.dismissed ===
true ? "zoomOut" : "zoomIn"} cursor-pointer`} key={key}
onClick={() => !n.dismissable || notifStore.close(key)}>
<div className={`${bg} rounded flex-1 shadow-md`}>
<p className={`${text} p-4`}>{n.message}</p>
</div>
</div>
);
});
return (
<div className="fixed z-50 w-full max-w-md h-auto top-0 right-0 pt-2">
{items}
</div>
);
})
Example #23
Source File: I18nProvider.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
I18nProvider = observer(({children, rtlLayout}: I18nProviderProps) => {
const mainStore = getMainStore()
const getDirection = useCallback(() => {
const rtlCondition = rtlLayout
|| localesStore.isRtlLayout(mainStore.locale);
return rtlCondition ? 'rtl' : 'ltr';
}, [rtlLayout, mainStore?.locale])
const i18n = getI18n();
if (!mainStore || !mainStore.locale) {
return null;
}
return (
<RawIntlProvider value={i18n}>
<ConfigProvider
locale={antdLocalesStore.antdLocaleMapping[mainStore.locale]}
direction={getDirection()}
>
{children}
</ConfigProvider>
</RawIntlProvider>
);
})
Example #24
Source File: Navigation.tsx From eth2stats-dashboard with MIT License | 6 votes |
Navigation: React.FC = observer(() => {
const {store} = useStores();
const match = useRouteMatch();
store.changeNetwork(match.path);
return (
<React.Fragment>
<nav
className="fixed w-full flex flex-col sm:justify-center bg-darkblue-100 h-32 sm:h-24 z-30"
style={{top: store.getConfig().length > 1 && 48 || 0}}>
<div className="flex justify-between w-full py-4 sm:py-0">
<Logo network={store.networkName}/>
<div className="flex items-center">
<NodesCount store={store}/>
{window.innerWidth >= 640 && <SlotStats store={store}/>}
<Menu networkPath={store.getNetworkConfig()!.path}
currentPath={store.path}/>
</div>
</div>
{
window.innerWidth < 640 &&
<div className="flex sm:hidden w-full p-4 justify-center">
<SlotStats store={store}/>
</div>
}
</nav>
<BottomNav joinURL={store.getNetworkConfig()!.joinURL}/>
</React.Fragment>
);
}
)
Example #25
Source File: WishlistModal.tsx From Cromwell with MIT License | 6 votes |
WishlistModal = observer(() => {
const handleClose = () => {
appState.isWishlistOpen = false;
}
return (
<Modal
className={clsx(commonStyles.center)}
open={appState.isWishlistOpen}
onClose={handleClose}
blurSelector={"#CB_root"}
>
<div className={clsx(styles.wishlistModal)}>
<IconButton
aria-label="Close wishlist"
onClick={handleClose} className={styles.closeBtn}>
<CloseIcon />
</IconButton>
<h3 className={styles.modalTitle}>Wishlist</h3>
<MuiWishlist elements={{ ProductCard }}
classes={{ root: styles.list }}
/>
</div>
</Modal>
)
})
Example #26
Source File: TableHead.tsx From eth2stats-dashboard with MIT License | 6 votes |
TableHead: React.FC = observer(() => {
const { store } = useStores();
// TODO not used ?
// function handleClick(id: string) {
// console.log(id);
// store.clientStore.setSort(id);
// }
return (
<div className="py-4 w-full bg-darkblue-100 hidden sm:block">
<div className="flex">
{store.columns.map((item) => (
<TableHeadItem key={item.name} item={item} store={store} />
))}
</div>
</div>
);
})
Example #27
Source File: ViewedModal.tsx From Cromwell with MIT License | 6 votes |
ViewedModal = observer(() => {
const handleClose = () => {
appState.isWatchedOpen = false;
}
return (
<Modal className={clsx(commonStyles.center)}
open={appState.isWatchedOpen}
onClose={handleClose}
blurSelector={"#CB_root"}
>
<div className={clsx(styles.ViewedModal)}>
<IconButton
aria-label="Close recently viewed items"
onClick={handleClose} className={styles.closeBtn}>
<CloseIcon />
</IconButton>
<h3 className={styles.modalTitle}>Viewed Items</h3>
<MuiViewedItems elements={{ ProductCard }}
classes={{ root: styles.list }}
/>
</div>
</Modal>
)
})
Example #28
Source File: Map.tsx From eth2stats-dashboard with MIT License | 6 votes |
@observer
export class Map extends React.Component<IMapProps> {
render() {
const { store } = this.props;
return (
<React.Fragment>
<div className={`${store.getConfig().length > 1 && "mt-44 sm:mt-36" ||
"mt-32 sm:mt-24"} mx-auto`}>
<MapChart {...this.props} />
</div>
</React.Fragment>
);
}
}
Example #29
Source File: CartModal.tsx From Cromwell with MIT License | 6 votes |
CartModal = observer(() => {
const handleCartClose = () => {
appState.isCartOpen = false;
}
return (
<Modal
className={commonStyles.center}
open={appState.isCartOpen}
onClose={handleCartClose}
blurSelector={"#CB_root"}
>
<div className={styles.cartModal}>
<IconButton
aria-label="Close shopping cart"
onClick={handleCartClose} className={styles.closeBtn}>
<CloseIcon />
</IconButton>
<div className={styles.cartList}>
<MuiCartList onProductClick={handleCartClose} classes={{ cartTotal: styles.cartTotal }} />
</div>
<Link href="/checkout" onClick={handleCartClose} style={{ display: 'flex' }}>
<Button
aria-label={"Open checkout"}
className={styles.checkoutBtn}
variant="contained"
color="primary"
size="large"
startIcon={<ShoppingCartIcon />}
>Checkout</Button>
</Link>
</div>
</Modal>
)
})