How to listen to page url change in React? - css

I have a react component that is rendered in two different pages and I want it to have different css for each page. So I passed it a prop to switch between the css classes, but, because there is no page refresh between the 2 pages, my component doesn't change the css class, only if I manually refresh the page, my component sees the prop I passed and changes the css class.
Can anyone tell me how can I make the component rerender on page change ? even if there is no page refresh?
I tried, until now, to change the state of the component with componentDidUpdate, but it ends up rerendering on a infinite loop, and the page doesn't load anymore.
Is there any other way to do this ?

I think you can solve the problem using history. This will help you to track the URL changes.
if you're using a functional component you can use useParams
the second solution that comes to my mind is to use the param as the key of the component, that will force the re-render.

I imagine you are using react router dom, if so I think getting the location by doing useLocation() would achieve the desired result as when the url changes this hook would cause a re-render
const location = useLocation()

Related

How to use MobX obervables to cause a 3rd party React Component (FullCalendar) to render?

I am trying to wrap FullCalendar React component with my own functional React component with useContext hook to access MobX store (I might use the store in other components eventually) and observer() to make it react to changes in the store. My component reacts as I would expect, but I have trouble making the FullCalendar component render after a change.
I've tried finding a solution, wrapping <FullCalendar> in <Observer>, playing with autorun() and reaction() but nothing worked. I have to be missing something
This sandbox https://codesandbox.io/s/mobx-fullcalendar-xejn9 shows a simplified version of my solution so far.
Clicking the button at the top adds an event to the observable store, which gets shown in a list below it. But the calendar doesn't show the new event.
Weirdly enough if I make a change in the code, save it, the CodeSandbox causes the render and the events show up in the calendar.
Thanks to #ADyson, I found a solution. Instead of passing a static list of events to the FullCalendar component
events={store.events}
I can pass an event fetching function. So in the most trivial case, I can just pass the events from the store to the successCallback function and it works.
events={(fetchInfo, successCallback, failureCallback) => {
successCallback(store.events);
}}
I've updated the CodeSandbox https://codesandbox.io/s/mobx-fullcalendar-xejn9 as well.

Component initialization with Iron Router, Jquery, Materialize

Struggling here with what would otherwise be a simple $( document ).ready().
Not sure what I'm doing wrong.
Materialize needs jquery components to be initialized on DOM ready. Finding a way to initialize components on all views is surprisingly tricky.
Here is the online DEMO
From reading the docs: this should initialize everything the sub-templates require:
Template.layout.rendered = function(){
$('ul.tabs').tabs()
}
}
However, this only works on a hard page refresh, and not with links routing the views.
So instead you would have to initialize on each template that element will be used
Template.x.rendered ...
Template.y.rendered ...
Here is the github code
BTW We've tried iron-router events:
onRun
onBeforeAction
onAfterAction
All of these seem to happen before the route's template content is present. I noticed that onBeforeAction required a call to this.next() to go on, I even tried looking for the DOM content after the next call.
I also tried rewriting our routes like this:
Router.route('someRoute', function() {
this.render('someRoute');
// look for DOM content, still not found
});
Just to be clear, the reason this is happening is because your layout is only firing the rendered hook once. When you switch routes the layout template will not be rerendered, only the templates in the yield region will be. The previous template in that region gets destroyed and the next one rerendered. This means you have to run $('ul.tabs').tabs() again for that Template as the DOM elements it contains are rerendered.
Putting that code in the rendered function of the template that uses it works because that rendered hook gets run every time that particular template gets rendered again.
A way you could get around this could be to create a Template specifically for your tabs, like a control in a way, that calls $('ul.tabs').tabs() in its own rendered function. You could then put this control on a template that needed it and pass the required arguments, like number of tabs and content for each tab etc. It's a bit of work though, and I'd only consider it if I had a really large number of templates that used the tab control.

Meteor JS Template rendered function called before template is rendered?

I'm trying to use the Buttonset widget in JQuery UI. I've got the package loaded and my template renders the radio buttons fine. I have a "rendered" function to call the JQ UI routine to setup the buttonset:
Template.teamList.rendered = function () {
$("#buttonsetID").buttonset();
}
But it looks like the rendered function is being called before the template is rendered! I stick a console.log in the function and it prints out to the console before there's anything on the screen. So none of the radio buttons are set up, therefore the .buttonset() call does nothing. If I make that call in the console after the page is rendered, JQuery UI does the right thing and my button set appears.
Isn't the .rendered function supposed to be called after everything's set up? Am I doing something wrong?
Thanks!
edit:
As an example, the same thing is seen in the leaderboard example.
If you add:
Template.leaderboard.rendered = function() {
alert($('.player').length);
}
When the page is displayed, it will show 0. This makes it difficult to access the DOM items if you need to add some JQuery events or, in this case, a JQuery UI element.
rendered only works for elements which will appear in the DOM the very first time the template is added to the page. Assume that subscription data takes infinitely long to arrive, then look at the template and see which elements would appear in the default state.
Using the leaderboard example, we can't assume that players are available when the leaderboard template renders (it depends on a subscription). To target a player, you should use the rendered callback on the player template.
It's hard to generalize a strategy for when to apply jQuery plugins, but here are some ideas:
Use the rendered callback if the element will always be added in the default state (e.g. the element is hard-coded and doesn't depend on a conditional).
Use the rendered callback of the most specific child template to target that child (e.g. the player template from above).
Consider using an event handler callback to target the element if it's appearance depends on an event (e.g. a button click).
Consider using a template autorun callback to target the element if it's appearance depends on reactive state. See this question for an example.

How to do page reveal animations with IronRouter?

I'm using meteor & IronRouter, and trying to do some javascript-driven animations when the template is ready/rendered.
However, the IR hook events don't seem to fire when they should.
onBeforeAction and onAfterAction only seem to fire before the new page is rendered.
So there is no updated DOM to animate.
I also tried overriding the action, calling render myself, and then animating.
however, the DOM is still not updated... even using Meteor.defer
action: ->
this.render() # works ok
Meteor.defer ->
Template.SceneView.animateScene()
This was still getting called while the old template was present. I guess since Meteor is still updating async-ly, and so defer() didn't really defer...
So a hack around this is to call the animate function from the template itself, and then also use Meteor.defer to call the animation, so the DOM is updated.
The Blaze rendered() hook only fires once on template creation.
Separately there are some new ui_hooks in Blaze, but these seem to be before insert or deletes happen. I guess I could use this and take over the whole DOM manipulation but that seems like overkill for just playing some animations when a page is ready...
https://github.com/percolatestudio/transition-helper/blob/master/transition-helper.js
UPDATE. I found out about the afterFlush event
So it seems that having reactive templates, somehow makes defer timing not work.
Instead if I use the following, the DOM is all updated in time for the animation trigger.
action: ->
this.render()
Deps.afterFlush ->
Template.SceneView.animateScene()
You could also use plain css, if you have a package like animate.css in your app (http://daneden.github.io/animate.css/)
If you have this class animated bounceIn on the div or element thats at the top of your template it will also display an animation when the template comes into view.

Is there a way for MVC Partial View retrieved using jQuery to keep UI CSS Styling?

I have an MVC 2 project, consisting of a MasterPageView a child View called Index and a number of PartialViews. The PartialViews are loaded into the Index View using the jQuery Ajax method $.get(....).
My problem is that I am styling the buttons using jQuery UI like:
$('button').button();
but I find that I need to do this on every PartialView. What I would like to do is define
this once in the MasterPageView, but if I do this the styling is lost. I'm guessing this
is because the styling is applied before the DOM is loaded, is this correct? Is there any
way to implement this i.e. just define it on the MasterPageView?
Thanks for the help !
This wont work when objects are added to the DOM after the initial load. In those cases you should go for the new .live() syntax in jQuery :
$("button").live("load", function(){
$(this).button();
});
It listens for new objects being added to the DOM and attaches an eventhandler to it..
Hope that helps!

Resources