I have a "login" screen (entering name only) with the button - without nav links. I want to make an additional screen with different content when the button is clicked, but I can't figure out how to do it.
React version: 18
I tried to add a router, but I didn't know how to set it against the components (I have no links or additional url).
To create a new screen in a React application, you can use a router and add routes for each of the screens in your app.
Install the react-router-dom package, which provides the components and functions you need to use routing in React.
npm install react-router-dom
Import the BrowserRouter, Route, and Link components from the react-router-dom package in your app's entry point (e.g. index.js):
import { BrowserRouter, Route, Link } from 'react-router-dom';
Wrap your app's root component with the BrowserRouter component to enable routing:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
Add a Route component for each screen in your app, specifying the path for the screen and the component that represents the screen. For example, to add a "Profile" screen, you could do the following:
function App() {
return (
<div>
{/* Other components and content here... */}
<Route path="/profile" component={Profile} />
</div>
);
}
Now add an onClick event on your button e.g
<button type="submit" onClick={onClick}>
Go to Profile
</button>
and this is how you can use:
function LoginForm() {
....
const navigate = useNavigate();
const onClick = () => navigate('/profile');
....
....
}
Related
so I have a react movie website which fetches data from tmbd , on home page it shows all trending movies data , and on the favorites page it shows all favorite movies , i routed these two pages but when i try to access favorites my browser gets really slow and tells me to stop the webpage , only after reloading the page , i get redirected to favorites page any solution in this ?
this is my nav bar where the links are , when i try to access the favourites page its shows that the page is slowing down
import React, { Component } from 'react'
import { Link } from "react-router-dom";
export default class Navbar extends Component {
render() {
return (
<div style={{display:'flex', padding:'0.5'}}>
<Link to="/" style={{textDecoration:'none'}}>
<h1 style={{marginTop:'1rem',marginLeft:'1rem'}}>Movies App</h1>
</Link>
<Link to='/favourites' style={{textDecoration:'none'}}>
<h2 style={{marginLeft :'5rem',marginTop:'2rem'}}>Favorites</h2>
</Link>
</div>
)
}
}
Here is my APP.js
import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import Navbar from './Components/Navbar';
import Banner from './Components/Banner';
import Movies from './Components/Movies';
import Favourite from './Components/Favourite';
import {Switch,Route, BrowserRouter,Routes} from 'react-router-dom';
function App() {
return (
// <>
// <Navbar></Navbar>
// <Banner></Banner>
// <Movies></Movies>
// </>
<BrowserRouter>
<Navbar/>
<Routes>
<Route exact path="/" element={<HomePage/>}/>
<Route exact path="/favourites" element={<Favourite/>}/>
</Routes>
</BrowserRouter>
);
}
function HomePage() {
return (
<>
<Banner />
<Movies />
</>
);
}
export default App;
when i try to access the individual file without routing it works fine ,but when i try to access this with routing my browser starts to slow down and the data isnt fetched untill i reload the page
my Github repo link: https://github.com/faizxmohammad/React-MovieApp/tree/master/src
I am expecting to fetch data of favorites pages without slowing down the browser
I cloned your code.
The problem is in the file Favorites.js, line 45. You are changing the state, inside the render method. This causes loops. Move any state change, outside render method. Why? This is the workflow:
State change -> renders the component
You are changing your state, inside render component, so it becomes:
state change -> render (state change inside so leads to state change) -> state change -> render render (state change inside so leads to state change) ... infinite loop.
I am new to javascript and react, and i am trying to route from one component to another when a button is clicked.
example of html code in the sign up page:
<!-- signup button -->
<div id = "signup">
<button class="signupbutton">Sign up</button>
</div>
so when the sign up button i want it to route to this html page:
<!-- page title -->
<h1><strong>Let's get started! First up, where are you in the planning process?</strong</h1>
Any ideas on how i can do this? - i know i need to do this in javascript and with react (i ahve created a JS file for the sign up page and planning process page), but i am a bit unsure of how to do so. Any ideas?
You can't link in HTML directly with React. You need to set up two components first.
One for the page with the Button:
export default function ButtonPage () {
return (
<div id = "signup">
<button className="signupbutton">Sign up</button>
</div>
);
}
One with the page for the Get Started Page:
export default function GetStarted () {
return (
<h1><strong>Let's get started! First up, where are you in the planning process?</strong</h1>
);
}
Then You need to set up your main component, the App component and link the child components you want to display. If you use the latest version of React you need to import BrowserRouter, Route and Routes from react-router-dom:
import { BrowserRouter, Route, Routes } from "react-router-dom";
export default function App () {
return (
<BrowserRouter>
<Routes>
<Route path="/signup" element={<ButtonPage/>}></Route>
<Route path="/getstarted" element={<GetStarted/>}></Route>
</Routes>
</BrowserRouter>
);
}
Then you need to import Link from react-router-dom inside your ButtonPage Component and Link to the other Component:
import { Link } from "react-router-dom";
export default function ButtonPage () {
return (
<div id = "signup">
<Link to="/getstarted">
<button className="signupbutton">Sign up</button>
</Link>
</div>
);
}
Et voilĂ : You linked two pages in React. For more information, look up the documentation of React-Router here.
I am using React Router.
I want when the user clicks on the button, it directs them to the page (endpoint) /form which has the UserForm component.
Here is my code wrapping the button:
<Router>
<Link to="/form" className="updateLink">
<button className="updateBtn" onClick={() => {
this.update(id);
console.log(`Item Number: ${id} Was Updated Successfully`);
window.alert(`Item Number: ${id} Was Updated Successfully`);
}}>U</button>
</Link>
<Switch>
<Router exact path="/form" component={UserForm} />
</Switch>
</Router>
So the reason that doesn't work is because the Button has its own click handler separate from the link handler. You have two options available to you:
Style the Link tag such that it looks like a button but don't actually look like a button (this won't work if you need to do additional logic in addition to routing)
Actually use a button. And then use the 'useHistory' React Hook React Router provides to get the functionality you're looking for.
The component would look something like this:
const history = useHistory()
return (
<Button onClick={() => history.push("/abc")}/>
)
I would personally recommend that you simply style the link tag in the way that you need it to. As that would be more accessible and understandable to the user. But that's only a good idea if you only care about the routing.
Is the above code accurate as in your code?
Router statement should be set up as below, usually in App.js
<Router>
<Switch>
<Route path = './form' component = {form}
</Switch>
</Router>
You then create the form component and to link to it you then import the link component in the component you wish to use it.
Then use as below
<Link to = './form'> Some Text </Link>
Onto the button issue you are having
It will render but you shouldn't nest an <a> or <button> tag in HTML as it wont be sematic for screenreaders, isn't accessible, nor it it valid HTML.
The Link element in react creates and renders an <a> tag which shouldn't be nested in a button.
You could use useHistory in your case for the same effect
import React from 'react'
import { useHistory } from 'react-router-dom'
const component = () => {
const { push } = useHistory()
...
<button
type="button"
onClick={() => push('/form')}>
Click me to go to a form!
</button>
...
}
I decided I need to stop using HasRouter, and instead, use BrowserRouter.
I switched out all my imports from:
import { HashRouter} from 'react-router-dom';
to
import { BrowserRouter } from 'react-router-dom';
As well as all my blocks:
<HashRouter>
to
<BrowserRouter>
My app nearly behaved as expected. All links in my app work fine.
For example:
<Link to={{pathname: `/budget/${item.id}`, state: params}}>{item.name}</Link>
Updated my URL as expected and navigates to the component.
My history works too:
handleEditRow(paymentNumber) {
this.props.history.push(`/schedule/${this.state.scheduleId}/event/${paymentNumber}`);
}
However, all my NavBar buttons fail. The URL updates as expected, but my app does not load the component:
I have my routes in :
return (
<Switch>
<Route exact path="/" component={Dashboard} />
<Route exact path="/accounts" component={Accounts} />
....
</Switch>
)
}
I'm assuming this works, as the links above are behaving.
In my NavBar, I just do simple links:
<Nav.Link as={NavLink} to='/accounts' exact>Accounts</Nav.Link>
I found a link that mentioned to use 'Link' instead of NavLink.
<Nav.Link as={Link} to='/accounts' exact>Accounts</Nav.Link>
But this still fails. URL updates, but page doesn't change.
As I say, the URL changes as expected, but the app does not load the app.
However, if I then select the URL in the address bar, and press Enter (Load the URL that it changed to), the app loads the correct component, as expected.
Can anyone spot my error?
It was working fine with HashRouter.
Just a quick tip: if you're not sure about which Router to use, you can import it aliased as "Router". You then don't have to change all HashRouter references to BrowserRouter if you decide to switch to another Router:
import { BrowserRouter as Router } from 'react-router-dom';
And then use:
<Router>
The advantage of this approach is that you only change the import and it works straight out of the box.
I have set up a basic react app with hash navigation. Problem is when I click on any link to navigate between pages, I see that the hash in the url is changing properly, as well as I added a console.log in my layour's render to see if it's getting called and it is, with proper this.props.children values, however the page is not rendering anything. If I go to any route and refresh the page I see the correct components rendered, but if I navigate somewhere from there noting gets rendered until I refresh again.
import React from "react";
import ReactDOM from "react-dom";
import { IndexRoute, Router, Route, Link, hashHistory as history } from 'react-router';
class Layout extends React.Component {
render() {
console.log(this.props, document.location.hash);
return <div>
<div>
<span>LEYAUTI MLEAYTI {Math.random()}</span>
</div>
<div>
{this.props.children}
</div>
<div>
{this.props.params.project}
</div>
</div>
}
}
class CreateProject extends React.Component {
render() {
return <div>
<h1>Create PROEKT</h1>
</div>
}
}
class Projects extends React.Component {
render() {
return <div>
<h1>PROEKTI MROEKTI</h1>
<Link to="/projects/create">New project</Link>
</div>
}
}
ReactDOM.render(
<Router history={history}>
<Route path="/" component={Layout}>
<IndexRoute component={Projects}/>
<Route path="projects/create" component={CreateProject}/>
</Route>
</Router>,
document.getElementById('app-root'));
Here is a visual of what's happening in the console when I navigate on a couple routes, but the DOM remains unchanged
This may be an issue with hashHistory. Which react-router version are you using? With v4 and above, you need to use history like so -
import createHistory from 'history/createHashHistory'
const history = createHistory()
// pass history to the Router....
Your component didn't actually unmount/remount if you only update your hashtag in your url. The route however, is updated. So you can only see the component loads content for once when you refresh the page.
You will need to create state variables and update it in a routeChange handler callback and bind the updated state variable to your view by using setState. Then the component can get updated.
See this post for how to add the route change listener (https://github.com/ReactTraining/react-router/issues/3554)
Alright, so I got down to the bottom of it.
The problem was that I was including my client.min.js file before the default app.js file of laravel 5.4's default layout. For some reason it broke react in a very weird way. What I had to do is switch the order in which the two files were included.