React Router Link dont updated page data - javascript

I have this react + redux app
I have 1 Movie component with some movie data displayed on it which are fetched from API.
So at the bottom, i decided to add a Similar movies section with a couple of components to navigate to the new movie pages.
<div className="similar_movieS_container">
{ this.props.thisMovieIdDataSIMILAR.slice(0,4).map((movie,index)=>{
return(
<Link to={"/movie/"+movie.id} key={index}>
<div className="similar_movie_container">
<div className="similar_movie_img_holder">
<img src={"http://image.tmdb.org/t/p/w185/"+movie.poster_path} className="similar_movie_img" alt=""/>
</div>
</div>
</Link>
)
})
}
</div>
Now when I'm at a root route for instance /toprated and i click on a <Link to={"/movie/"+movie.id} key={index}> i get navigated to the particular route (e.g. /movie/234525 ) and everything works fine , but if I'm in a /movies/{some move ID } route and i click on some <Link to={"/movie/"+movie.id} key={index}> The route in the URL bar gets updated, but the page stays still, meaning nothing changes if I reload the page with the new route the new movieID data is displayed...
So how can i make a navigation to a new /movie/{movieID} FOMR a /movie/{movieID} ?

It's because you are just within same route.
There are few ways to work around this. I bet you are rendering routes like this.
<Route path="/movie/:id" component={Movie} />
Try like this.
<Route path="/movie/:id" component={() => <Movie />} />
Another solution would be to use componentWillReceiveProps instead of componentWillMount.

This happens because the component of page movie was mounted, so the render method of this component will not be mounted again or updated, so you need to fire a code to change the state, and consequently re-rendering the page content, for this you can implement the componentDidUpdate method which is fired for every props modification.
https://reactjs.org/docs/react-component.html#componentdidupdate
Basically you implement the same code above inside

Related

How to implement data update from one component which might affect other components

I am implementing a todo application which has several pages where each page displays a filtered list of all todos depending on the todos' references.
In addition, there is a global "Add task" button and modal from which users can add a task with references. Depending on which page the user is on when adding a task, this newly added task must either be shown right away because the reference is included in currently active page's filter or it must not be shown.
For example, if the user is on the page "Project 1"
If user adds task for Project 1 -> show on page
If user adds task for Project 2 -> don't show on page
Currently, App.js looks something like this
function App() {
return (
<Page>
<Router>
<Route path="/project1" element={<TaskListProject1 />} />
<Route path="/project2" element={<TaskListProject2 />} />
<Router />
<AddTaskButtonAndModal />
<Page />
);
}
How do I best set up and manage the state so that the components TaskListProject1 and TaskListProject2 are only updated if the added task must be included there?
I was thinking about adding the task from the AddTaskButtonAndModal component to the data base and then let the currently active component retrieve all their tasks from the data base again. For this, I would introduce a dummy state whose sole purpose is triggering a rerender of components like so
function App() {
const [dummyState, setDummyState] = useState(0);
return (
<Page>
<Router>
<Route path="/project1" element={<TaskListProject1 dummyState={dummyState} />} />
<Route path="/project2" element={<TaskListProject2 dummyState={dummyState} />} />
<Router />
<AddTaskButtonAndModal setDummyState={setDummyState} />
<Page />
);
}
...but that feels like I'm misusing states.
Another idea was to always have a complete list of all tasks in the top level state and let each component filter for their tasks when it is rendered. But then I need to always have all tasks in the state when only a fraction of tasks are actually needed.
As you can probably imagine, I'm new to React, so I might simply miss a basic concept. Thanks for any help!

React router url changes correctly but component not being rendered from button component link

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>;

Routing to specific part of other component in React

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.

How to get local state of another component using Redux

Using react + redux, I am making an app where you answer questions, 5 questions per step and about 20 steps. When starting a new step, I save the progress to localStorage.
My app structure is like this:
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div id="ocean-model">
<Topbar />
<main id="main">
<Route exact path="/" component={Landing} />
<Switch>
<PrivateRoute exact path="/survey" component={Survey} />
</Switch>
<Switch>
<AdminRoute exact path="/edit-questions" component={EditQuestions} />
<AdminRoute exact path="/add-question" component={AddQuestion} />
</Switch>
</main>
</div>
</Router>
</Provider>
);
}
}
In Survey component I use controlled inputs to save current answers to local state and on submitting all 5 answers I use redux action to save given answers to localStorage and redux store.
In Topbar component I have a button, which onClick I would like to take the current progress from redux store, but also get the currently answered questions(for example 2 out of 5), which are only available in the Survey component's local state.
Do I need to modify the App structure so that Topbar and Survey can share state or maybe in Survey I need to somehow listen to an onclick event of a button from Topbar?
Is there any reason you can't save given answer to localStorage and redux store when the input loses focus? Might need to allow for the action to fire if the Topbar component button is clicked while the focus is still on the last input with an answer.
The alternative would be to use React Context as your state container for each set of 5 questions and use that from both the form and the Topbar button with a Provider located in the component tree above both.

call a component function from header componet in react router

Her is my index.js file, layout(header, middel-container, footer)
<div>
<Header />
<div className="middle-container">
<Route path="/hello" component={HelloWorldApp} />
<Route exact path="/" component={Login} />
</div>
<Footer />
</div>
I have separate file for Header, HelloWorldApp, Login and footer. On my Header component there have login button, if I click on login button it will call a function on Login component.
How I can I do that. (This is not a child, parent component so that I can pass the function name as props.)
Please help me.
Import {Link} from react-router-dom in your login component. Add a Link to "/" like **abc. If you want to call a method inside the login component(That way it should be a class component..) then You should instead try to add that state of login component in your index.js component and then you can call login stateless functional component by sending the state as props to it so you can get the desire results.
Here is an example of calling a stateless functional component:
login({[your_state_as_props]})=>
return([conclusion of your operations on props..]);
further more you can read here https://medium.com/#ruthmpardee/passing-data-between-react-components-103ad82ebd17
and if you want to pass to data between two totally separate components,(HelloWorlApp and Login) then you can... but it will totally mess up all of your program. Instead hold any data that you require to send down to child components in your topmost component or make Helloworld component a method of your main component if its a functional component or if not, try to hold it's state in your topmost component and make helloworld a method of of your first component.

Categories

Resources