I'm creating a simple react app. I need to load a component from a button click. When I click the edit button I need to load the edit component. I tried it using <Link>. But I can't understand how to give the relative path. It means it need to load it like http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e/edit. I need to load it from http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e. How can I give the relative path?
App.js
<Provider store={configureStore()}>
<BrowserRouter>
<div className="App">
<LayoutWrapper>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/viewTicket/:id" exact component={ViewTicket} />
<Route path="/viewTicket/:id/edit" exact component={EditTicket} />
</Switch>
</LayoutWrapper>
</div>
</BrowserRouter>
</Provider>
Ticket.js
<Link to="/viewTicket/:id/edit">
<Button size="lg" onClick={this.handleEdit}>
<Pencil />
Edit
</Button>
</Link>
But url lokks like this.
Is there any other way to do this?
You forgot to include the actual ID in the URL. You're just directing the user to this literal string that has ":id" in it:
<Link to="/viewTicket/:id/edit">
Whatever your ID values is (for demonstration let's assume it's in a variable called id), you'd use that to build your URL:
<Link to={`/viewTicket/${id}/edit`}>
As an aside, this is a very strange structure and will likely lead to confusion:
<Link to="/viewTicket/:id/edit">
<Button size="lg" onClick={this.handleEdit}>
Putting a button inside of a link means that you're trying to simultaneously do two different things. Should this.handleEdit be invoked? Or should the user be redirected by the link? It's best to invoke a single operation. If some logic needs to happen inside of this.handleEdit before redirecting the user, then remove the <Link> and manually redirect the user (likely using the useHistory hook) after performing that logic.
Related
I have something similar to the following CodeSandBox example where I need to use react routing within two different components.
The problem that I am facing is that, if using this codesandbox example and I click down to either the Profile or Quotes component level and assuming I have the following Material-UI button within each of these bottom components:
<Button>
text="New Item"
variant="outlined"
className={classes.newButton}
component={NewItem}
to={'/new-item'}
</Button>
When clicking on this "New Item" button, the URL changes to the correct route, i.e. /new-item but the actual NewItem component is not being rendered in the page?
If I refresh the browser, then it loads correctly.
Can anyone pls assist with the above and what the best solution is, when at this level?
Arthur, make sure in your index.js or wherever you are declaring your switch its set up like so.
<Switch>
<Route exact path="/NewItem" component={NewItem}/>
</Switch>
Then you can simply add a nav link like so
<Link to="/NewItem">New Item</Link>
the button will have a component of Link which is imported from react-router-dom
<Button>
text="New Item"
variant="outlined"
className={classes.newButton}
component={Link}
to="/new-item"
</Button>
and in the app.js you will create a Route like so :
<Switch>
<Route exact path="/NewItem" component={NewItem}/>
</Switch>
Well you shouldn't use button for changing go to new Page or going new URL. rather than use
<link to=""/> for routing but if you want to use button for going to different page than use Redirect from react-router-dom
import { Redirect } from 'react-router-dom';
const Next = (e) => {
e.preventDefault();
return <Redirect to='/NewItem' />;
};
<Button onClick={Next}>
text="New Item" variant="outlined" className={classes.newButton}
component={NewItem}
</Button>;
Or you can use Link using Link
import {Link} from 'react-router-dom';
<Link to={'/NewItem'} className={classes.newButton}>
New Item
</Link>;
Suppose that you have Page1 and Page2 and I want to retrieve one page using one link called
<Link to="/question/:question_id"
The route is defined like this
<Route path ="/question/:question_id" render={(props)=> prop.hasAnswer? <Page1 /> : <Page2 /> }>
However, when I click on this route it always retrieves Page2
very new to react router. i know this code isn't written the cleanest but how come when i click the button (Link to='/question') it renders
and BUT also renders the button still. i tried
setting it into a new route but unfortunately still doesn't work.
also is this how you would structure a basic router that needs to
render two separate components? i see i can do render={} or component={}
but not really sure how to render more than one component with one
router---- wit those two questions considered i basically just want
this button to render a new page ('/question') that has two components on it--- AFIB and QFIB and nothing else (right now its rendering the button and the two new components in addition... here is the code:
<div class='qAndAContainer'>
<Router>
<Link to='/question'><button className="px-4 nextQuestion startButton py-2 bg-pink-600 text-white text-sm uppercase font-medium rounded hover:bg-pink-500 focus:outline-none" >Begin
</button>
</Link>
<Route path='/question' component={(props) => (
<QFIB {...props} />
)} />
<Route path='/question' component={(props) => (
<AFIB {...props} />
)} />
</Router>
</div>
)
}
export default StartTest
React Router's Route component is basically a glorified string-match for your browser's URL.
In this case, what you're presenting to React Router is three Routes with the same strings to match, so it shows them all!
This is actually useful, for example rendering the same navigation bar for /dashboard AND /dashboard/messages.
But in your case, you just want one route or the other. So for React Router to understand you just want one of many, you need to wrap your Routes with a Switch component. React Router will only render the first match it finds, from top to bottom. Try to order your Routes in a Switch from most specific (longest paths) to least to get the best results.
I don't really care for the render or children props of Route (although they have their purposes), I usually prefer composing just like normal components.
<Router>
<Switch>
// this will actually match /question123/asdf/kdkd?foo=bar as well...
<Route path="/question">
<QFIB />
<AFIB />
</Route>
// `exact` tells the Route is must be... exact
<Route path="/" exact>
<Link to="/question">Go to Questions</Link>
</Route>
</Switch>
</Router>
I have a problem with routing to a specific part of another functional component in React.
I have declared Route in Main component and Link around the place where I want to redirect from... it looks like this...
The main function gets:
<Switch>
<Route exact path='/news/:eyof' component={News} />
<Route exact path='/news/:svetsko' component={News} />
<Route exact path='/news' component={News} />
</Switch>
And I defined in other functional component:
<div className="card">
<Link to="/news/:svetsko">
<div className="card-header">
<h3>Artistic gymnastics world championship</h3>
</div>
</Link>
</div>
So by clicking on this link, I need to get redirected to News page class "svetsko" so I can read about that news... All news are in containers in same page....
Try something like this in your component:
let { scrollToSection } = useParams();
svetskoRef = React.createRef();
useParams() allows you to access :svetsko. When the component loads, you can use scrollToSection to navigate between different parts of the page. The scrollRef is used to access the DOM element you want to scroll to.
window.scrollTo(0,scrollRef.offsetTop)
The markup would look something like this:
<div className="card" ref="svetskoRef">
<Link to="/news/:svetsko">
<div className="card-header">
<h3>Artistic gymnastics world championship</h3>
</div>
</Link>
</div>
You need only one route like
<Switch>
<Route exact path='/news' component={News} />
</Switch>
you can give link like
<Link to={{
pathname: '/news',
state: { news : yourNewsName } // you can pass svetsko here
}}>
<div className="card-header">
<h3>Artistic gymnastics world championship</h3>
</div>
</Link>
You can access this state in your News Page like
<div>{ props.location.state !== undefined ? props.location.state.news : '' }</div>
After getting your news type like eyof :
Step 1 :
you can create on functional component which takes argument as your
data and return your new post jsx with your data.
Step2 :
So,when you get your eyof in your page then you are going to call
this function and pass your data related to your eyof and that function
return your new post to your page.
Ok, I found one really good library as a solution, it's called react-scroll and it has an option to wrap link you need in earlier defined scroll link, and to wrap component you want it to link as a specific part of the page with Element with id you gave to scroll link as a parameter... Try it if you need it somehow.
I've noticed a strange behavior in react-router.
I have my routes defined like so:
var routes = (
<Route name='app' path='/' handler={Master}>
<DefaultRoute handler={HomePage} />
{/* inject:route */}
<Route name='home' handler={HomePage} />
<Route name='issues' handler={IssuesPage} />
<Route name='security' handler={SecurityPage} />
<Route name='contactUs' handler={ContactUsPage} />
<Route name='docs' handler={DocsPage} />
{/* endinject */}
<Redirect from='/' to='/home' />
<NotFoundRoute handler={HomePage}/>
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler />, document.body);
});
in our fork of https://github.com/shovon/generator-react-material-ui.
Clicking links in the LeftNav produces expected results.
Upon starting gulp, the redirect from / to /home works.
What seems weird and undesirable is when I type in something like http://localhost:3000/#/some-undefined-route.
As expected, the DefaultRoute handler takes over, and the home page content is visible. HOWEVER, the weird URL remains. What I would expect is for any undefined route to redirect to a pre-defined catch-all. For example, I want http://localhost:3000/#/some-undefined-route to automatically redirect to http://localhost:3000/#/home -- not just show that content.
We're trying to use a mixin with transitionTo() to achieve the desired effect, but I'm still wondering if anybody knows the "right" way to handle this. I also wonder if what I'm seeing is actually the intended react-router behavior. If I'm missing something, I'd love to be enlightened. Cheers!
Update
From taurose at react-router:
Have you tried
<Redirect from="*" to=".." />
when responding to https://github.com/rackt/react-router/issues/732.
What might help anybody else with a similar question is to be aware that you will have to provide a Redirect for each sub-route, as well.
Apparently, this set up is designed to allow more detailed route control and handling of things like 404s.
Initially, we suspected that might be the case, but I didn't understand how the splat ( from="*" ) works.
Maybe this will be useful to others.
Cheers.