React not updating the DOM (Laravel) - javascript

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.

Related

React JS : this page is slowing down firefox, to speed up the browser , stop this page

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.

How to switch the screen after clicking the button?

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');
....
....
}

How can i route from one HTML page to another in react js?

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.

if function is not up to date react

I'm new in this amazing site, I'm just having a problem in my react app.
this is the index.js I'm using react-router-dom in this page I just need to show this.state.show for who is in a home page, So in the login.js request I've created 'loginToken' with this code sessionStorage.setItem('loginToken', 'Value')
and now I'm making a verification for sessionStorage.getItem('loginToken') in index.js
Everything works fine but my problem is when I'm in a home page this text 'Welcome Back' doesn't appears automatically I need to refresh the home page to see it. I don't know why this happening.
Is it because I'm using componentWillMount?
I've tried to use componentDidMount I got same problem
import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './users/login';
import home from './news/index';
class App extends Component {
constructor(props){
super(props);
this.state = {
show: false
}
}
componentWillMount(){
if(sessionStorage.getItem('loginToken')){
this.setState({show: true});
}else{
this.setState({show: false});
}
}
render() {
return (
<div>
{this.state.show?
<div>welcome back</div>:null
}
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/home" component={home} />
</Switch>
</Router>
</div>
)
}
}
export default App;
Thank you so much for helping me.
This issue is componentWillMount only fires once when the app first is run since it is the most top level component in the tree.
You should look to pass a function as a prop into the Login component and call it in the login component to trigger a state change back in the parent component. You could follow an approach to doing so in this article.
The easiest approach would be to just move that welcome back text into a dashboard or home route this way it mounts and unmounts as you are expecting and you can use your current approach in that component.

React Router V4 is updating URL, but not refreshing (React, Redux)

I am trying to use React-Router V4 to add routes to my app, but it is not working at all. Basically, I'm trying to programatically change the route with history.push, which is updating the browser URL, but not changing anything inside the actual app.
NOTE: I am using redux.
The only answered question on this issue is:
React history.push() is updating url but not navigating to it in browser
However, I've tried the answer to the above question, and it doesn't work for me.
Here are the important snippets:
Topmost file (index.js)
...
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App/>
</Provider>
</BrowserRouter>
, document.getElementById('root'));
...
Component containing routes
...
export default function ContentRouter() {
return <div className="content">
<Route exact path="/dashboard" component={TmpDashboard}/>
<Route exact path="/" component={() => {
return <h1>Home</h1>
}}/>
</div>
}
Component pushing routes
...
this.handleGroupClick = (group) => {
this.props.history.push(`/groups/${group}`);
this.props.onOpenChange(false);
};
...
export default withRouter(connect(mapStateToProps, mapDispatchToProps(DrawerConnector))
After a lot of searching in the completely wrong place, I figured out what was wrong. The lack of updating was being caused by Redux
Whenever a component is wrapped in connect it causes updates to be blocked, and the view doesn't update.
The solution is mentioned here:
https://github.com/ReactTraining/react-router/issues/4671#issuecomment-285320076
Basically, every component with a Route or a React-Router thing inside it must be wrapped with withRouter
EDIT: Only the top level component that uses connect should be wrapped in withRouter. Note that this may cause performance issues
EDIT: The way I got around the increased coupling was to have a component just to deal with routes. That way, I only need to wrap that component, and the component with a Router.
Here's a setup that works:
The main App:
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
/* this is a common component and happens to need to redirect */
<Route component={CommonComponentThatPushesToHistory} />
<div id="body">
/* I usually place this switch in a separate Routes file */
<Switch>
<Route exact path="FooRoute" component={FooPage}/>
<Route exact path="BarRoute" component={BarPage}/>
</Switch>
</div>
/* another common component which does not push to history */
<Footer />
</div>
</BrowserRouter>
);
}
}
export default withRouter(App);
CommonComponentThatPushesToHistory
class CommonComponentThatPushesToHistory extends React.Component{
render(){
return(
<button type="button"
onClick={() => {this.props.history.push('some-page');}}>
Click to get redirected</button>
);
}
}
FooPage may have a child component that pushes to history:
class FooPage extends React.Component{
render(){
return(
<MyChild history={this.props.history} />
);
}
}
Then MyChild component can push to history the same way CommonComponentThatPushesToHistory does.

Categories