react-router-dom#withRouter JavaScript Examples
The following examples show how to use
react-router-dom#withRouter.
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: Menu.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
Menu = withRouter(({history}) => (
<AppBar position="static">
<Toolbar>
<Typography variant="h6" color="inherit">
MERN Skeleton
</Typography>
<Link to="/">
<IconButton aria-label="Home" style={isActive(history, "/")}>
<HomeIcon/>
</IconButton>
</Link>
<Link to="/users">
<Button style={isActive(history, "/users")}>Users</Button>
</Link>
{
!auth.isAuthenticated() && (<span>
<Link to="/signup">
<Button style={isActive(history, "/signup")}>Sign up
</Button>
</Link>
<Link to="/signin">
<Button style={isActive(history, "/signin")}>Sign In
</Button>
</Link>
</span>)
}
{
auth.isAuthenticated() && (<span>
<Link to={"/user/" + auth.isAuthenticated().user._id}>
<Button style={isActive(history, "/user/" + auth.isAuthenticated().user._id)}>My Profile</Button>
</Link>
<Button color="inherit" onClick={() => {
auth.clearJWT(() => history.push('/'))
}}>Sign out</Button>
</span>)
}
</Toolbar>
</AppBar>
))
Example #2
Source File: RequireAuthentication.js From Lambda with MIT License | 6 votes |
export default function RequireAuthentication(Component) {
class Authentication extends React.Component {
render() {
return (
<Route
render={(props) => {
return this.props.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location },
}}
/>
);
}}
/>
);
}
}
Authentication.propTypes = {
isAuthenticated: PropTypes.bool,
};
function mapStateToProps(state) {
return {
isAuthenticated: state.user.isAuthenticated,
};
}
return withRouter(connect(mapStateToProps)(Authentication));
}
Example #3
Source File: nodes-chart.js From ThreatMapper with Apache License 2.0 | 6 votes |
NodesChart = withRouter(({ onNodeClicked, match }) => (
<div className="">
{menu.map(menuItem => (
<Route
key={menuItem.id}
exact
path={`${match.path}/${menuItem.id}`}
render={() =>
<menuItem.component
onNodeClicked={onNodeClicked}
showPanelForNode={showPanelForNode}
/>
}
/>
))}
<Route
exact
path={match.path}
render={() => <Redirect to={`${match.url}/${menu[0].id}`} />}
/>
</div>))
Example #4
Source File: App.js From enrollar with MIT License | 6 votes |
function App() {
const location = useLocation();
return (
<AnimatePresence exitBeforeEnter>
<span location={ location } key={ location.key }>
<Route exact path="/sign-up" component={ withRouter(Auth) } />
<Route exact path="/sign-in" component={ withRouter(Auth) } />
<Route path="/home" component={ withRouter(Search) } />
<Route exact path="/" component={ withRouter(Homepage) } />
</span>
</AnimatePresence>
)
}
Example #5
Source File: index.js From choerodon-front-base with Apache License 2.0 | 6 votes |
StoreProvider = withRouter(injectIntl(inject('AppState')(
(props) => {
const { AppState: { currentMenuType: { type, id } }, intl, children, context } = props;
const { applicationId, versionCreateDataSet } = context;
const appServiceVersionDataSet = useMemo(() => new DataSet(AppServiceVersionDataSet({ id, intl, applicationId, versionCreateDataSet })), [id]);
const intlPrefix = 'project.application-management.list';
const value = {
...props,
prefixCls: 'application-management',
intlPrefix,
applicationId,
projectId: id,
appServiceVersionDataSet,
};
return (
<Store.Provider value={value}>
{children}
</Store.Provider>
);
},
)))
Example #6
Source File: App.js From TrackCOVID-community with MIT License | 6 votes |
function App () {
const history = createBrowserHistory()
const AppContainerWithRouter = withRouter(AppContainer)
return (
<Router basename={basename}>
<AppContainerWithRouter history={history} />
</Router>
)
}
Example #7
Source File: routes.js From react-portfolio with MIT License | 6 votes |
AnimatedSwitch = withRouter(({ location }) => (
<TransitionGroup>
<CSSTransition
key={location.key}
timeout={{
enter: 400,
exit: 400,
}}
classNames="page"
unmountOnExit
>
<Switch location={location}>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={ContactUs} />
<Route path="*" component={Home} />
</Switch>
</CSSTransition>
</TransitionGroup>
))
Example #8
Source File: router-4.jsx From virtuoso-design-system with MIT License | 6 votes |
Home = withRouter(props => {
const { location } = props;
const pathSnippets = location.pathname.split('/').filter(i => i);
const extraBreadcrumbItems = pathSnippets.map((_, index) => {
const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
return (
<Breadcrumb.Item key={url}>
<Link to={url}>{breadcrumbNameMap[url]}</Link>
</Breadcrumb.Item>
);
});
const breadcrumbItems = [
<Breadcrumb.Item key="home">
<Link to="/">Home</Link>
</Breadcrumb.Item>,
].concat(extraBreadcrumbItems);
return (
<div className="demo">
<div className="demo-nav">
<Link to="/">Home</Link>
<Link to="/apps">Application List</Link>
</div>
<Switch>
<Route path="/apps" component={Apps} />
<Route render={() => <span>Home Page</span>} />
</Switch>
<Alert style={{ margin: '16px 0' }} message="Click the navigation above to switch:" />
<Breadcrumb>{breadcrumbItems}</Breadcrumb>
</div>
);
})
Example #9
Source File: MapUS.js From covid-19 with MIT License | 6 votes |
CountyNavButtons = withRouter((props) => {
const county = props.county;
const state = county.state();
const metro = county.metro();
const history = props.history;
return <ToggleButtonGroup
value={null}
exclusive
size="large"
onChange={(e, route) => {
history.push(route);
}}
>
<ToggleButton size="small" value={county.routeTo()} >
{county.name}
</ToggleButton>
{metro &&
<ToggleButton value={metro.routeTo()} >
{metro.name} </ToggleButton>
}
<ToggleButton value={state.routeTo()} >
{state.name}</ToggleButton>
</ToggleButtonGroup>;
})
Example #10
Source File: Menu.js From Full-Stack-React-Projects-Second-Edition with MIT License | 5 votes |
Menu = withRouter(({history}) => (
<AppBar position="fixed" style={{zIndex:12343455}}>
<Toolbar>
<Typography variant="h6" color="inherit">
MERN Classroom
</Typography>
<div>
<Link to="/">
<IconButton aria-label="Home" style={isActive(history, "/")}>
<HomeIcon/>
</IconButton>
</Link>
</div>
<div style={{'position':'absolute', 'right': '10px'}}><span style={{'float': 'right'}}>
{
!auth.isAuthenticated() && (<span>
<Link to="/signup">
<Button style={isActive(history, "/signup")}>Sign up
</Button>
</Link>
<Link to="/signin">
<Button style={isActive(history, "/signin")}>Sign In
</Button>
</Link>
</span>)
}
{
auth.isAuthenticated() && (<span>
{auth.isAuthenticated().user.educator && (<Link to="/teach/courses"><Button style={isPartActive(history, "/teach/")}><Library/> Teach</Button></Link>)}
<Link to={"/user/" + auth.isAuthenticated().user._id}>
<Button style={isActive(history, "/user/" + auth.isAuthenticated().user._id)}>My Profile</Button>
</Link>
<Button color="inherit" onClick={() => {
auth.clearJWT(() => history.push('/'))
}}>Sign out</Button>
</span>)
}
</span></div>
</Toolbar>
</AppBar>
))
Example #11
Source File: common.js From actual with MIT License | 5 votes |
ButtonLink = withRouter(ButtonLink_)
Example #12
Source File: ConnectedErrorMessage.jsx From Learning-Redux with MIT License | 5 votes |
ConnectedErrorMessage = withRouter( connect(mapStateToProps)(ErrorMessage) )
Example #13
Source File: Details.js From citr-v6-project with Apache License 2.0 | 5 votes |
DetailsWithRouter = withRouter(Details)
Example #14
Source File: CategoryMenuContainer.jsx From covid-trials-dashboard with MIT License | 5 votes |
CategoryMenuContainer = withRouter(withWidth()(Container))
Example #15
Source File: AdvMock.js From YApi-X with MIT License | 5 votes |
module.exports = Form.create()(withRouter(AdvMock));
Example #16
Source File: QueryFileUploader.js From ui-data-export with Apache License 2.0 | 5 votes |
QueryFileUploader = stripesConnect(withRouter(QueryFileUploaderComponent))
Example #17
Source File: slideNav.js From ant-simple-pro with MIT License | 5 votes |
enhance = composes(
withRouter,
connect(({ user }) => ({
getMenuTree: user.getMenuTree,
loadingMenuTree: user.loadingMenuTree
}))
)
Example #18
Source File: index.jsx From makerverse with GNU General Public License v3.0 | 5 votes |
ProtectedRoute.propTypes = { ...withRouter.propTypes, };
Example #19
Source File: OftadehNavCollapse.jsx From oftadeh-react-admin with MIT License | 5 votes |
NavCollapse = withRouter(React.memo(OftadehNavCollapse))
Example #20
Source File: withMoviesNav.jsx From movies with MIT License | 5 votes |
function withMoviesNav(WrappedComponent) {
const MoviesNav = (props) => {
const dispatch = useDispatch();
function update(nextValues) {
const { location } = props;
const nextUrlParams = {
...qs.parse(location.search),
...nextValues
};
redirect(`/?${qs.stringify(nextUrlParams)}`);
}
// Movies type switching handler (used in toolbar in movies list page)
function changeMoviesType(moviesType) {
update({ moviesType, page: 1 });
}
// Pagination handler
function linkPage({ selected }) {
update({ page: selected + 1 });
}
/*
Handler for routing to the movie details page.
Used from the list of movies, search results or recommendations
*/
function linkMovie(id) {
const { location } = props;
const { lng } = qs.parse(location.search);
dispatch(resetMovieDetails());
redirect(`/movies/${id}?${qs.stringify({ lng })}`);
}
const {
moviesType = DEFAULT_MOVIES_TYPE
} = qs.parse(props.location.search);
return (
<WrappedComponent
activeMoviesType={moviesType}
changeMoviesType={changeMoviesType}
linkPage={linkPage}
linkMovie={linkMovie}
{...props}
/>
);
};
MoviesNav.propTypes = {
location: PT.shape({
search: PT.string.isRequired
}).isRequired
};
return withRouter(MoviesNav);
}
Example #21
Source File: index.js From choerodon-front-base with Apache License 2.0 | 5 votes |
StoreProvider = withRouter(injectIntl(inject('AppState')(
(props) => {
// 是否为项目层客户端
const isProject = props.match.url.includes('pro-client');
const {
AppState: {
currentMenuType: {
id, type, organizationId, projectId,
},
}, children, intl,
} = props;
const intlPrefix = 'c7ncd.client';
const formatCommon = useFormatCommon();
const formatClient = useFormatMessage(intlPrefix);
const orgId = type === 'organization' ? id : organizationId;
const clientStore = useStore();
const optionsDataSet = useMemo(
() => new DataSet(OptionsDataSet(orgId, isProject, projectId)), [orgId, isProject, projectId],
);
const clientDataSet = useMemo(
() => new DataSet(ClientDataSet(orgId, isProject, projectId, formatClient)), [orgId],
);
const remoteMobxStore = useLocalStore(() => ({
disableAllBtn: false,
get getDisableAllBtn() {
return remoteMobxStore.disableAllBtn;
},
setDisable(status) {
remoteMobxStore.disableAllBtn = status;
},
}));
const value = {
projectId,
orgId,
id,
clientDataSet,
optionsDataSet,
remoteMobxStore,
intl,
intlPrefix,
clientStore,
isProject,
formatCommon,
formatClient,
};
return (
<Store.Provider value={value}>
{children}
</Store.Provider>
);
},
)))
Example #22
Source File: MovieCard.js From petio with MIT License | 5 votes |
MovieCard = withRouter(MovieCard);
Example #23
Source File: EditSignatureContainer.jsx From signdocs with MIT License | 5 votes |
SignatureContainer = withRouter( connect(mapStateToProps, mapDispatchToProps)(EditSignature), )
Example #24
Source File: SearchHome.jsx From intergalactic with MIT License | 5 votes |
SuggestSearch = withRouter(connectAutoComplete(connectStateResults(Search)))
Example #25
Source File: App.js From bedav with GNU General Public License v3.0 | 5 votes |
LiveRoute = withRouter(NotLiveRoute)
Example #26
Source File: App.js From react-portfolio with MIT License | 5 votes |
ScrollToTop = withRouter(_ScrollToTop)
Example #27
Source File: App.js From covid-19 with MIT License | 5 votes |
MainApp = withRouter((props) => {
const [earth, setEarth] = React.useState(null);
const [country, setCountry] = React.useState(null);
const [myCounty, setMyCounty] = React.useState(null);
const [nonUSCountry, setNonUSCountry] = React.useState(null);
const ROW_special = props.location.pathname.startsWith("/country")
&& !props.location.pathname.startsWith("/country/US");
React.useEffect(() => {
if (ROW_special) {
createBasicEarthAsync().then(data => setEarth(data));
}
const myCountry = new Country();
setCountry(myCountry);
fetchApproximatePoliticalLocation().then(countyDescr => {
if (countyDescr.country === "United States of America" || countyDescr.county) {
const county = makeCountyFromDescription(myCountry, countyDescr);
setMyCounty(county);
logger.logEvent("AppStart", {
myCounty: county,
});
} else {
setNonUSCountry(countyDescr.country);
}
});
}, [ROW_special]);
if ((ROW_special && earth === null) || country === null) {
return <Splash />
}
if (props.location.pathname === "/") {
if (myCounty) {
return <Redirect to={reverse(routes.county, {
state: myCounty.state().twoLetterName,
county: myCounty.name,
})} />;
}
if (nonUSCountry) {
const search = earth.get(SEARCH_INDEX_PATH, SearchIndexComponent);
console.log("----------------------------:" + nonUSCountry);
console.log(nonUSCountry);
const allMatches = search.search(nonUSCountry);
if (allMatches && allMatches.length > 0) {
return <Redirect to={"/country" + allMatches[0].path.string()} />;
}
}
return <Splash />
}
if (ROW_special) {
return (
<WorldContext.Provider value={earth}>
<CountryContext.Provider value={country}>
<SafeRoutes />
</CountryContext.Provider>
</WorldContext.Provider>
);
};
return (
<CountryContext.Provider value={country}>
<SafeRoutes />
</CountryContext.Provider>
);
})
Example #28
Source File: DashboardNav.js From video-journal-for-teams-fe with MIT License | 4 votes |
DashboardNav = withRouter((props) => {
// Use location from router as a key to show that link is selected.
const {
// location,
// organization_id,
organizations,
userId,
fetchUserOrganizations,
defaultOrganization,
selectedOrganization,
fetchUserTeams,
setUserSelectedOrganization,
children,
} = props;
const { Sider } = Layout;
const { Title } = Typography;
const [showModal, setShowModal] = useState(false);
const location = useLocation();
let organization_id = "";
if (typeof selectedOrganization === "undefined" || typeof defaultOrganization === "undefined") {
organization_id = "";
} else {
organization_id = selectedOrganization.id ? selectedOrganization.id : defaultOrganization.id;
}
function handleClick(item) {
setUserSelectedOrganization(item);
// history.push('/user-dashboard');
}
const toggleModal = () => {
setShowModal(!showModal);
};
let filteredOrg = organizations.filter((x) => x.id === organization_id);
const menu = (
<Menu>
{organizations.map((item) => (
<Link key={item.id} to="/user-dashboard">
<Menu.Item style={{ textAlign: "center", color: "#FF7F50" }} key={item.id} onClick={() => handleClick(item)}>
{item.name}
</Menu.Item>
</Link>
))}
<Menu.Item>
<Organization />
</Menu.Item>
</Menu>
);
return (
<Sider breakpoint="lg" collapsedWidth="0" width="240" style={{ backgroundColor: "#6954EA" }}>
<div className={"userDashHeader"} style={{ backgroundColor: "#6954EA" }}>
<Title level={3}>
<Link
to="/user-dashboard"
className={"userDashHeaderFont"}
style={{ color: "whitesmoke", marginTop: "12px" }}>
<div className="logo">
<img src={logo} alt="logo" />
</div>
</Link>
</Title>
</div>
<Menu style={{ backgroundColor: "#6954EA" }} mode="inline" className={"userDashMenu"}>
<Dropdown overlay={menu} trigger="click">
<a
className="ant-dropdown-link"
onClick={(e) => e.preventDefault()}
style={{ display: "block", width: "500" }}>
<div style={{ paddingLeft: "25px", color: "white", width: "200px", textOverflow: "ellipsis" }}>
<BankOutlined style={{ paddingRight: "16px" }} />
{selectedOrganization.hasOwnProperty("name")
? selectedOrganization.name
: defaultOrganization
? defaultOrganization.name
: ""}
<DownOutlined />
</div>
</a>
</Dropdown>
<hr style={{ margin: "25px 0" }} />
<Menu.Item key="/user-dashboard">
<Link to="/user-dashboard" style={{ backgroundColor: "#6954EA", color: "#fff", display: "block" }}>
<Icon type="home" theme="filled"/> Dashboard
</Link>
</Menu.Item>
<Menu.Item key="/profile">
<Link to="/profile" style={{ color: "#FFF", display: "block" }}>
<Icon type="user" /> My Profile
</Link>
</Menu.Item>
<Menu.Item key="/videos">
<Link to="/videos" style={{ color: "#FFF", display: "block" }}>
<Icon type="play-circle" theme="filled" /> My Videos
</Link>
</Menu.Item>
{filteredOrg.length > 0 && filteredOrg[0].role_id === 3 ? (
<Menu.Item key="/teams">
<Link to={`/organizations/${organization_id}/teams`} style={{ color: "#FFF", display: "block" }}>
<Icon type="calendar" theme="filled" /> All Teams
</Link>
</Menu.Item>
) : null}
{filteredOrg.length > 0 && filteredOrg[0].role_id === 3 ? (
<Menu.Item key="/users">
<Link to={`/organizations/${organization_id}/users`} style={{ color: "#FFF", display: "block" }}>
<Icon type="calendar" theme="filled" /> All Users
</Link>
</Menu.Item>
) : null}
<Menu.Item key="/results">
<Link to="/results" style={{ backgroundColor: "#6954EA", color: "#fff", display: "block" }}>
<PieChartFilled /> My Results
</Link>
</Menu.Item>
<hr style={{ margin: "40px 0" }} />
{/* <Menu.Item key="/setting" disabled>
<Icon type="setting" theme="filled" />
Teams Settings
</Menu.Item>
<h3 style={{ color: "white", paddingLeft: "24px", paddingBottom: "20px" }}>Team Controls</h3>
<Menu.Item key="/manage-teams" disabled>
<Icon type="calendar" theme="filled" />
<span>Manage Teams</span>
</Menu.Item>
<Menu.Item key="/team-archive" disabled>
<Icon type="folder" theme="filled" />
<span>Team Archive</span>
</Menu.Item> */}
</Menu>
</Sider>
);
})
Example #29
Source File: index.js From choerodon-front-base with Apache License 2.0 | 4 votes |
Client = withRouter(observer(() => {
const {
clientDataSet, optionsDataSet, orgId, clientStore, isProject, projectId,
formatCommon,
formatClient,
} = useContext(Store);
function openEditRecordModal(record) {
clientDataSet.current = record;
Modal.open({
key: editKey,
title: formatClient({ id: 'edit' }),
children: <EditRecord
dataSet={clientDataSet}
record={clientDataSet.current}
clientStore={clientStore}
isProject={isProject}
projectId={projectId}
/>,
style: {
width: 380,
},
drawer: true,
okText: formatCommon({ id: 'save' }),
});
}
async function openCreateRecordModal() {
let initData;
if (isProject) {
initData = await axios.get(`/iam/choerodon/v1/organizations/${orgId}/clients-project/${projectId}/createInfo`);
} else {
initData = await axios.get(`/iam/choerodon/v1/organizations/${orgId}/clients/createInfo`);
}
initData.accessTokenValidity = 3600;
initData.refreshTokenValidity = 3600;
initData.autoApprove = 'default';
initData.scope = 'default';
initData.additionalInformation = '{}';
await clientDataSet.create(initData);
Modal.open({
key: createKey,
title: formatClient({ id: 'add' }),
children: <CreateRecord isProject={isProject} dataSet={clientDataSet} />,
style: {
width: 380,
},
drawer: true,
okText: formatClient({ id: 'addtext' }),
});
}
async function openRoleManageModal(record) {
clientDataSet.current = record;
const roleData = await clientStore.loadClientRoles(orgId, record.get('id'), isProject, projectId);
const roleIds = (roleData || []).map(({ id: roleId }) => roleId);
await record.set('roles', roleIds || []);
Modal.open({
key: roleKey,
title: `为客户端"${record.get('name')}"分配角色`,
children: <EditRole
optionsDataSet={optionsDataSet}
organizationId={orgId}
ds={clientDataSet}
dataSet={optionsDataSet}
record={clientDataSet.current}
isProject={isProject}
projectId={projectId}
/>,
style: {
width: 380,
},
drawer: true,
okText: formatCommon({ id: 'save' }),
});
}
function handleRowClick(record) {
openEditRecordModal(record);
}
async function handleDelete(record) {
Modal.open({
title: formatClient({ id: 'delete' }),
children: `确认删除客户端"${record.get('name')}"吗?`,
maskClosable: false,
okText: formatCommon({ id: 'delete' }),
onOk: async () => {
try {
await axios.delete(
isProject
? `/iam/choerodon/v1/organizations/${orgId}/clients-project/${projectId}/${record.get('id')}`
: `/iam/choerodon/v1/organizations/${orgId}/clients/${record.get('id')}`,
);
await clientDataSet.query();
} catch (err) {
message.prompt(err);
}
},
});
}
function handleRoleClick(record) {
openRoleManageModal(record);
}
const renderAction = ({ record }) => {
const actionDatas = [{
service: [`choerodon.code.${isProject ? 'project' : 'organization'}.setting.client.ps.delete`],
text: <FormattedMessage id="organization.client.delete.title" />,
action: () => handleDelete(record),
}, {
service: [`choerodon.code.${isProject ? 'project' : 'organization'}.setting.client.ps.role`],
text: '角色分配',
action: () => handleRoleClick(record),
}];
return <Action data={actionDatas} />;
};
const filterData = (record) => record.status !== 'add';
const renderName = ({ text, record }) => (
<Permission
service={[`choerodon.code.${isProject ? 'project' : 'organization'}.setting.client.ps.update`]}
defaultChildren={(<span>{text}</span>)}
>
<span role="none" className="link" onClick={() => handleRowClick(record)}>
{text}
</span>
</Permission>
);
return (
<Page service={[`choerodon.code.${isProject ? 'project' : 'organization'}.setting.client.ps.default`]}>
<Header>
<HeaderButtons
showClassName={false}
items={([{
name: formatClient({ id: 'add' }),
icon: 'playlist_add',
display: true,
permissions: [`choerodon.code.${isProject ? 'project' : 'organization'}.setting.client.ps.add`],
handler: openCreateRecordModal,
}])}
/>
</Header>
<Breadcrumb />
<Content className="organization-pwdpolicy">
<Table pristine filter={filterData} dataSet={clientDataSet} className="tab2">
<Column renderer={renderName} width={250} name="name" align="left" />
<Column width={60} renderer={renderAction} />
<Column name="authorizedGrantTypes" width={500} />
</Table>
</Content>
</Page>
);
}))