I have a problem in nested routing in React.js.
The presenter component has this.
<Route
exact
path={`/course/${id}/assignment`}
render={(props) => (
<CourseAssignments
{...props}
courseId={id}
data={assignmentData}
/>
)}
/>
And here is CourseAssignments component at /course/${id}/assignment.
const CourseAssignments: React.FC<RouteComponentProps & IProps> = ({
courseId,
data,
match,
}) => {
return (
<Container>
<Route
exact
path={match.path}
render={(props) => (
<AssignmentList {...props} courseId={courseId} data={data} />
)}
/>
<Route path={`${match.path}/:id`} component={AssignmentSubmit} />
</Container>
);
};
The AssignmentList renders well at course/0/assignment.
const AssignmentList: React.FC<RouteComponentProps & IProps> = ({
match,
courseId,
data,
}) => {
return (
<div>
{data.map((d) => (
<div key={d.id}>
<Link to={`${match.url}/${d.id}`}>{d.title}</Link>
</div>
))}
</div>
);
};
I use <Link />, it links to course/0/assignment/:id.
But course/0/assignment/1 doesn't render AssignmentSubmit component.
I don't know why it doesn't work. Pleaze help.
(env is localhost)
Related
I'm updating a sourcecode from react-router-5 to version 6. So far I'm getting this error:
Error: [div] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
The bug is triggered when I activate a link in this component(QuoteItem.js):
const QuoteItem = (props) => {
return (
<li className={classes.item}>
<figure>
<blockquote>
<p>{props.text}</p>
</blockquote>
<figcaption>{props.author}</figcaption>
</figure>
<div className={classes.item}>
<Link className='btn' to={`/quotes/${props.id}`}>View Fullscreen</Link>
</div>
</li>
);
};
in another component (VerQuotes) I defined the routes:
const VerQuotes = () => {
return (
<div>
<main>
<Layout>
<Routes>
<Route path="quotes" element={<AllQuotes />} />
<Route path="new-quote" element={<NewQuote />} />
<Route path="quotes/:quoteId" element={<QuoteDetail />} />
</Routes>
</Layout>
</main>
</div>
);
};
I'm kind of lost how to tackle the error, your comments will be highly appreciated.
Thanks a lot
Update
QuoteDetail
const QuoteDetail = () => {
const match = useNavigate();
const params = useParams();
const { quoteId } = params;
const { sendRequest, status, data: loadedQuote, error } = useHttp(getSingleQuote, true);
//const quote = DUMMY_NOTES.find((quote) => quote.id === params.quoteId);
useEffect(() => {
sendRequest(quoteId);
}, [sendRequest, quoteId]);
if(status === "pending"){
return (
<div className="centered">
<LoadingSpinner />
</div>
);
}
if(error){
return <p className="centered">{error}</p>;
}
if (!loadedQuote.text) {
return <p>No Quote Found!</p>;
}
return (
<Fragment>
<HighlightedQuote text={loadedQuote.text} author={loadedQuote.author} />
<Routes>
<Route path={match}>
<div className="centered">
<Link
className="btn--flat"
to={`${match}/comments`}
>
Load Comments
</Link>
</div>
</Route>
<Route path={`${match}/comments`} element={<Comments />}></Route>
</Routes>
</Fragment>
);
};
Issues
After tracing your code I found you had a couple issues in QuoteDetail component.
You used const match = useNavigate(); (so match is really the navigate function) but then later used match to attempt to form a path string for a Route.
The Route component's children prop is only for rendering nested routes. The error you see is the use of the div element that isn't a Route component.
Code
<Routes>
<Route path={match}>
<div className="centered">
<Link
className="btn--flat"
to={`${match}/comments`}
>
Load Comments
</Link>
</div>
</Route>
<Route path={`${match}/comments`} element={<Comments />}></Route>
</Routes>
Solution
Remove const match = useNavigate(); since it is not used, and place the div into the element prop of the Route. Change the path props to use relative routing from the current route path that's already been built up.
const QuoteDetail = () => {
const params = useParams();
const { quoteId } = params;
const { sendRequest, status, data: loadedQuote, error } = useHttp(
getSingleQuote,
true
);
//const quote = DUMMY_NOTES.find((quote) => quote.id === params.quoteId);
useEffect(() => {
sendRequest(quoteId);
}, [sendRequest, quoteId]);
if (status === "pending") {
return (
<div className="centered">
<LoadingSpinner />
</div>
);
}
if (error) {
return <p className="centered">{error}</p>;
}
if (!loadedQuote.text) {
return <p>No Quote Found!</p>;
}
return (
<Fragment>
<HighlightedQuote text={loadedQuote.text} author={loadedQuote.author} />
<Routes>
<Route
path="/"
element={
<div className="centered">
<Link className="btn--flat" to="comments">
Load Comments
</Link>
</div>
}
/>
<Route path="comments" element={<Comments />} />
</Routes>
</Fragment>
);
};
I am using React Router v6 in an application. I have a layout page, which uses an outlet to then show the main content. I would also like to include a title section that changes based on which path has been matched, but I am unsure how to do this.
function MainContent() {
return (
<div>
<div>{TITLE SHOULD GO HERE}</div>
<div><Outlet /></div>
</div>
);
}
function MainApp() {
return (
<Router>
<Routes>
<Route path="/projects" element={<MainContent />} >
<Route index element={<ProjectList />} title="Projects" />
<Route path="create" element={<CreateProject />} title="Create Project" />
</Route>
<Routes/>
</Router>
);
}
Is something like this possible? Ideally, I would like to have a few other props besides title that I can control in this way, so a good organization system for changes like this would be great.
The most straightforward way would be to move the title prop to the MainContent layout wrapper and wrap each route individually, but you'll lose the nested routing.
An alternative could be to create a React context to hold a title state and use a wrapper component to set the title.
const TitleContext = createContext({
title: "",
setTitle: () => {}
});
const useTitle = () => useContext(TitleContext);
const TitleProvider = ({ children }) => {
const [title, setTitle] = useState("");
return (
<TitleContext.Provider value={{ title, setTitle }}>
{children}
</TitleContext.Provider>
);
};
Wrap the app (or any ancestor component higher than the Routes component) with the provider.
<TitleProvider>
<App />
</TitleProvider>
Update MainContent to access the useTitle hook to get the current title value and render it.
function MainContent() {
const { title } = useTitle();
return (
<div>
<h1>{title}</h1>
<div>
<Outlet />
</div>
</div>
);
}
The TitleWrapper component.
const TitleWrapper = ({ children, title }) => {
const { setTitle } = useTitle();
useEffect(() => {
setTitle(title);
}, [setTitle, title]);
return children;
};
And update the routed components to be wrapped in a TitleWrapper component, passing the title prop here.
<Route path="/projects" element={<MainContent />}>
<Route
index
element={
<TitleWrapper title="Projects">
<ProjectList />
</TitleWrapper>
}
/>
<Route
path="create"
element={
<TitleWrapper title="Create Project">
<CreateProject />
</TitleWrapper>
}
/>
</Route>
In this way, MainContent can be thought of as UI common to a set of routes whereas TitleWrapper (you can choose a more fitting name) can be thought of as UI specific to a route.
Update
I had forgotten about the Outlet component providing its own React Context. This becomes a little more trivial. Thanks #LIIT.
Example:
import { useOutletContext } from 'react-router-dom';
const useTitle = (title) => {
const { setTitle } = useOutletContext();
useEffect(() => {
setTitle(title);
}, [setTitle, title]);
};
...
function MainContent() {
const [title, setTitle] = useState("");
return (
<div>
<h1>{title}</h1>
<div>
<Outlet context={{ title, setTitle }} />
</div>
</div>
);
}
...
const CreateProject = ({ title }) => {
useTitle(title);
return ...;
};
...
<Router>
<Routes>
<Route path="/projects" element={<MainContent />}>
<Route index element={<ProjectList title="Projects" />} />
<Route
path="create"
element={<CreateProject title="Create Project" />}
/>
</Route>
</Routes>
</Router>
I was facing the same issue for a left-right layout: changing sidebar content and main content, without repeating styling, banner, etc.
The simplest approach I found was to remove nested routing, and create a layout component in which I feed the changing content through properties.
Layout component (stripped for this post):
export function Layout(props) {
return (
<>
<div class="left-sidebar">
<img id="logo" src={Logo} alt="My logo" />
{props.left}
</div>
<div className='right'>
<header className="App-header">
<h1>This is big text!</h1>
</header>
<nav>
<NavLink to="/a">A</NavLink>
|
<NavLink to="/b">B</NavLink>
</nav>
<main>
{props.right}
</main>
</div>
</>
);
}
Usage in react router:
<Route path="myPath" element={
<Layout left={<p>I'm left</p>}
right={<p>I'm right</p>} />
} />
Another solution is to use the handle prop on the route as described in the useMatches documentation.
import { useMatches } from "react-router-dom";
function MainContent() {
const matches = useMatches()
const [title] = matches
.filter((match) => Boolean(match.handle?.title))
.map((match) => match.handle.title);
return (
<div>
<div>{title}</div>
<div><Outlet /></div>
</div>
);
}
function MainApp() {
return (
<Router>
<Routes>
<Route path="/projects" element={<MainContent />} >
<Route index element={<ProjectList />} handle={{ title: "Projects" }} />
<Route path="create" element={<CreateProject />} handle={{ title: "Create Project" }} />
</Route>
<Routes/>
</Router>
);
}
I'm a bit new to React and it is my first time using reach-router (or any kind of router really). What I'm trying to do is have a nested component inside one of my router links. Basically, within my ItemShop component, I want to have two more links to components (both of which are defined within my ItemShop component), and I want to display whichever component is selected under the navbar. It seems similar to something they do in the tutorial, but for some reason I seem to get an infinite loop when I click on a link.
Here is my top-level router, in App.js:
function App() {
return (
<div>
<Router>
<HomePage path="/" />
<ItemShop path="ItemShop" />
<Item path="ItemShop/:id" />
<Challenge path="Challenge" />
<Achievements path="Achievements" />
<BattlePass path="BattlePass" />
<Miscellaneous path="Miscellaneous" />
</Router>
</div>
);
}
And this is my ItemShop component where I'm trying to render the links, ItemShop.js:
render() {
// ... assigning arrays here
let Current = () => ( //...);
let Upcoming = () => ( //...);
return(
<>
<div className="nav-container">
<Navbar />
</div>
//...
<div>
<nav className="side-nav">
<Link to="/current">Current</Link>{" "}
<Link to="/upcoming">Upcoming</Link>
</nav>
<Router>
<Current path="current" />
<Upcoming path="upcoming" />
</Router>
</div>
//...
{this.props.children}
)
}
}
Again I am very new to Javascript/React as a whole, so it could just be a fundamental flaw. I have already sunk quite a few hours into this so I would really appreciate some guidance. Thank you for your time!
I tried using React-Router-Dom instead of reach-router. I made it so it renders both <Upcoming /> and <Current /> components inside of the <ItemShop /> component. You can check it out how I have done it below. I hope this helps.
// import React from "react";
// import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
export default function App() {
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/itemShop" component={ItemShop} />
<Route path="/itemShop/:id" component={Item} />
<Route path="/challenge" component={Challenge} />
<Route path="/achievements" component={Achievements} />
<Route path="/battlePass" component={BattlePass} />
<Route path="/miscellaneous" component={Miscellaneous} />
</Switch>
</Router>
</div>
);
}
const HomePage = () => {
return <div>Home Page</div>;
};
const ItemShop = () => {
const Current = () => {
return <div>Current</div>;
};
const Upcoming = () => {
return <div>Upcoming</div>;
};
return (
<div>
<div>Item Shop</div>
<Link to="/itemShop/current">Current</Link>{" "}
<Link to="/itemShop/upcoming">Upcoming</Link>
<br />
<br />
<Route
render={() =>
window.location.pathname === `/itemShop/current` ? (
<Current />
) : (
<Upcoming />
)
}
/>
</div>
);
};
const Item = () => {
return <div>Item</div>;
};
const Challenge = () => {
return <div>Challenge</div>;
};
const Achievements = () => {
return <div>Achievements</div>;
};
const BattlePass = () => {
return <div>BattlePass</div>;
};
const Miscellaneous = () => {
return <div>Miscellaneous</div>;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/6.0.0-beta.0/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have this Router, any page that should has the Layout is wrapped with the withLayout HOC.
I need to pass to some of the pages the user context, how can I add a user prop?
const withLayout = () => Component => props => (
<div css={pageWrap}>
<Header user={props.user} />
<Component {...props} />
</div>
);
export default function Router() {
return (
<AuthConsumer>
{({ user }) => (
<Switch>
<Route exact path="/" component={withLayout()(Home, { user })} />
<Route exact path="/page1" component={withLayout()(Page1)} />
<Route exact path="/page2" component={withLayout()(Page2)} />
</Switch>
)}
</AuthConsumer>
);
}
I think you have problem with your withLayout. It should be:
const withLayout = () => (Component, props = {}) => (
<div css={pageWrap}>
<Header user={props.user} />
<Component {...props} />
</div>
);
What's AuthConsumer?
You could use contextType = AuthContext inside your page components. [from]
class MyClass extends React.Component {
static contextType = MyContext;
render() {
let value = this.context;
/* render something based on the value */
}
}
I was able to get this to work like this:
<Route exact path="/" render={props => withLayout()(Home)({ ...props, user })} />
I am trying to create some protected in routes in React, using Create React App 2 and React Router 4. I used Tyler McGinnis's Protected Routes article as an example. Here is the my basic app component.
class App extends Component {
constructor(props) {
super(props);
this.state = { loggedIn: false };
}
componentDidMount() {
console.log('did mount');
this.setState({ loggedIn: true });
}
render() {
fakeAuth.authenticate(this.state.loggedIn);
console.log('render');
return (
<Router>
<Fragment>
<Login />
<PrivateRoute path="/register" component={Register} />
<Chordsheets />
<Chordsheet />
</Fragment>
</Router>
);
}
}
export default App;
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props => (
fakeAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to="/" />
)}
/>
);
const fakeAuth = {
isAuthenticated: false,
authenticate(state) {
this.isAuthenticated = state;
console.log('isAuthenticated', this.isAuthenticated);
}
};
const Login = () => (
<div>
<Route exact path="/" component={LoginForm} />
</div>
);
const Chordsheets = () => (
<Fragment>
<Route path="/chordsheets" component={Header} />
<Route path="/chordsheets" component={AllChordSheets} />
</Fragment>
);
const Chordsheet = () => (
<Fragment>
<Route path="/chordsheet/:id" component={Header} />
<Route path="/chordsheet/:id" component={ChordSheet} />
</Fragment>
);
const Header = () => {
return (
<header>
<nav className="links">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/chordsheets/0">My Chordsheets</Link>
</li>
</ul>
</nav>
</header>
);
};
After the component mounts loggedIn is set to true. When going to a new route render is not called again, so I cannot get to the Register route.
Does anyone have any thoughts on how to structure this? Thanks!
I know that i'm late but i'm happy to help anyone he wants this functionality by taking a look to this protected-react-routes-generator
All you're going to do is to provide the routes as an array.