How to not re-render React component's specific DOM elements? - javascript

Recently I started to refactor my Backbone web app with React and I'm trying to write interactive graph visualization component using react and sigma.js.
I roughly understood React's declarative paradigm and how it is implemented by render() method using jsx syntax.
But what gets me stumbled is a situation where I cannot define my React component declarativly.
It is because of the javascript-generated DOM elements, which only can be generated on componentDidMount() after the declarative DOM elements are rendered by render().
It makes me worried about both performance and buggy animations (my graph animates on instantiation time, which will be re-played on every render() calls in this situation)
My current code looks like:
...
render: function() {
return (
<div class="my-graph-visualization-component">
{/*
This div is defined declaratively, so won't be re-rendered
on every `change` events* unless `React`'s diff algorithm
think it needs to be re-rendered.
*/}
<div class="my-declarative-div">{this.props.text}</div>
{/*
This div will be filled by javascript after the `render()`
call. So it will be always cleared and re-rendered on every
`change` events.
*/}
<div class="graph-container MY-PROBLEM-DIV"></div>
</div>
);
},
componentDidMount: function() {
this.props.sigmaInstance.render('.graph-container', this.props.graph);
}
...
Is there any way to do something like
render: function() {
return (
<div class="my-graph-visualization-component">
<div class="my-declarative-div">{this.props.text}</div>
{/*
Any nice workaround to tell react not to re-render specific
DOM elements?
*/}
<div class="graph-container NO-RE-RENDER"></div>
</div>
);
},
so that my sigma.js graph component won't get re-instantiated with identical starting animation on every change on states?
Since it seems to be it is about handling non-declarative part of react components, any workarounds for this kind of problem will be appreciated.

The cleanest way is to define react sub-components and re-render what you really need instead of re-rendering the whole block
render: function() {
return (
<div class='myStaticContainerNotupdated'>
<SubComponentToUpdateOften/>
<MyGraph/>
</div>
)
}
The other solution could be to work on your graph and implement a singleton so your animation is only played once at the first render.
But really the easiest and cleanest thing I see is to create clean separate subcomponent and update them when needed. You never update the big container component just the subs one.
Hope it helps

You can use dangerouslySetInnerHTML. This basically tells React to stay away from it’s content and it wont evaluate/update it when doing it’s DOM diffing.

Related

How to make a React.js inline portal for a jQuery Datepicker

I've watched,
http://youtu.be/z5e7kWSHWTg?t=15m17s
and read,
https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md
https://github.com/ryanflorence/react-training/tree/gh-pages/code/Dialog
http://jsbin.com/dutuqimawo/edit?js,output
How to create a React Modal(which is append to `<body>`) with transitions?
and I get the concept of the Portal, that you're tricking React into ceasing its rendering for one piece of the DOM, then continuing the rendering afterward, so you can tinker with that piece of the DOM without confusing React by making its virtual DOM get out of sync.
My problem is that the examples all address a Dialog that is rendered at the end of the page, but appears inline when you're reviewing your code. It's a cool trick for using a jQuery modal, but I need a jQuery datepicker whose div actually remains where I put it. (As an aside, I'm also curious about GetDOMNode's presence in the examples when it's deprecated? I suppose you use FindDOMNode, although you call it slightly differently, plus the documentation says "In most cases, use of this escape hatch is discouraged because it pierces the component abstraction", which makes me a little gunshy to use it.)
To isolate the jQuery datepicker from React, I originally created one React component to handle everything above the datepicker, and another to handle everything below the datepicker, and used event listeners in each component to listen for updates. However, I prefer the design of a single parent component that passes everything down to its children; it seems like a cleaner design.
I redesigned it with a single parent and it seems to work, but I have no idea if my portal is really isolated from React's virtual DOM or not; it's my first crack at a portal so I'm really muddling through. (I am using React-Bootstrap for my navbar and it works great; I just couldn't find an equivalent to jQuery's datepicker and I like how it looks and operates, which is why I'm sticking with it.)
Here's my top-level component (I removed the props/componentDidMount/etc for clarity). The <CalendarControl /> is going to be the portal:
var ReactApp = React.createClass({
render: function() {
return (
<div>
<BootstrapNavbar division={this.state.division} dps={this.state.dps} sections={this.state.sections} />
<div className="container">
<br />
<br />
<br />
<div className="row">
<div className="col-md-4" id="calendarPortal">
<CalendarControl />
</div>
<div className="col-md-8">
<h3>{this.state.dp}</h3>
<h4>{this.state.dpStartDate} - {this.state.dpEndDate}</h4>
</div>
</div>
<TimebookTableRecords timebookRecords={this.state.timebookRecs} />
</div>
</div>
);
}
});
Here's the code for my CalendarControl portal. When the CalendarControl mounts, I'm creating a new div calendarControl as a child of calendarPortal. I then use jQuery to create the datepicker on the calendarControl div.
var CalendarControl = React.createClass({
render: function () {
return null;
},
componentDidMount() {
var portalLocation = document.getElementById("calendarPortal");
var newElement = document.createElement('div');
newElement.id = "calendarControl";
portalLocation.appendChild(newElement);
},
componentWillUnmount() {
var portalLocation = document.getElementById("calendarPortal");
document.body.removeChild(portalLocation);
},
});
Here's the jQuery code that creates a datepicker on the calendarControl div:
$("#calendarControl").datepicker({
numberOfMonths: monthDiff,
defaultDate: dpStartDate,
showButtonPanel: false,
beforeShowDay: formatCalendarDays, //formatter function
onSelect: dateClicked //handles click on calendar date
The final product seems to work fine, and doesn't generate any "the DOM was unexpectedly mutated" errors like when you manipulate part of the DOM that's under React's purview. I can update the state of the parent and see the changes propagate down nicely, and use jQuery to update the calendar.
However, I just don't know if this is the correct approach? That is to say, have I achieved a true portal here? I used the Google Chrome React Developer Tools add-in to inspect the component hierarchy, and it does look like from React's perspective there's a null in the CalendarControl div:
Thanks for bearing with me in this lengthy post. I have to say that so far I'm really loving the React approach to web development; it's so radically different that it took a number of readings and tinkering just to understand its concepts, but now it seems so much more elegant than the ways I've done it in the past.
From my understanding of portals, you are doing this mostly correct. But if it had any other children, you would have to reconnect with react after the jquery stuff, but I assume that is not the case here.
The reason you are seeing a "null" inside calendar control is because you return a null in your CalendarControl render function.
Why don't you just change your render function in calendarControl to:
render: function () {
return (
<div id="calendarControl"></div>
)
and do all your funky jQuery rendering inside componentDidMount function?

Can I avoid re-rendering parent route handler component when the route changes?

I'm noobies in react / redux and I'm looking to create modal view following this 3 rules :
who is url dependant
who is generic
who is optimized
Cause of the url dependancy it's not optimized, it's rerender the parent.
Example: I have a view namespaces view at '/namespaces' who print all namespaces and when I open '/namespaces/edit' who open the modal view the namespaces is rerender. How to not rerender the namespaces list ?
Below the Router
<Route path="namespaces" component={NamespaceList}>
<Route path="edit" component={NamespaceEdit}/>
<Route path="create" component={NamespaceCreate}/>
</Route>
NamespacesList component
function NamespacesList({ push, children }) {
console.log("rendered !")
return (
<div>
NamespacesList
<p>
<Link to="/namespaces/create">Create</Link>
<br />
<Link to="/namespaces/edit">Edit</Link>
</p>
{children}
</div>
)
}
NamespacesCreate component (printed inside of the modal)
const NamespacesCreate = function() {
return (
<Modal>
NamespacesCreate
<p>
<Link to="/namespaces">Back to namespaces list ?</Link>
</p>
</Modal>
)
}
Use case :
I'm on the /templates/create (namespacelist is drawing in the back of the modal, in the console rendered ! is printed then when I click to link to comeback to the parent url /templates, rendered ! is printed again.
So there is a way to "optimize" it and not rerender the namespaceList or I need to choose between, or am I wrong ?
Don’t worry about how many times the component’s render() method is called. Rendering is very cheap in React, and if the content has not changed, it will not actually touch the DOM.
You should only start worrying about render() method calls when you start to experience real performance problems in your app which is very unlikely for one-off things like navigations. For example, you might want to optimize animations or form components that have ton of inputs.
If and when you have this problem (not earlier!), you can check out React guides to Advanced Performance optimizations, measuring wasted renders with ReactPerf, and learn about common performance anti-patterns.
Don’t let this complicate your code for no reason though. Only optimize when you have a real problem, and no sooner. React is very fast for most users’ needs out of the box, and render() method being called often is perfectly fine.

Having trouble building a simple audio player in React using HTML5

I've recently started learning React and I'm trying to build a simple audio player. I'm currently using this example as a reference but it's built in one file
https://github.com/CezarLuiz0/react-cl-audio-player
The one I'm trying to make is done in a "React" way where the UI has reusable components but I'm having trouble separating my code into meaningful and working components. For example, if I try to move some of the rendering code from the parent component (AudioPlayer) into (PlayButton), the audio methods that is created on the mounting of the parent component suddenly becomes inaccessible to the child components.
Here is my code repo.
https://github.com/vincentchin/reactmusicplayer
It works now but I'd like to improve it. Also it'd be great if someone can point out huge flaws in this since I'm sure I've broken some rules or standards to coding in React.
You can access parent component's methods from a child component by passing the method as a prop, and then invoking it inside the child component.
For example (in the child component's render method):
<button onClick={this.props.methodFromTheParent}>Click me</button>
You can also pass arguments to these methods:
<button onClick={this.props.methodFromTheParent.bind(null, 'Hello')}>Click me</button>
Remember to pass in null instead of this as the first argument when binding values to a method belonging to a parent component.
I skimmed through your repo as well. You could clean up the AudioPlayer component a lot by putting the different elements into their own components.
The render method could look something like this:
render() {
return (
<div>
<PlayButton onClick={this.togglePlay} playing={this.state.playing} />
{!this.state.hidePlayer ?
(<Player
playerState={this.state}
togglePlay={this.togglePlay}
setProgress={this.setProgress}
...
/>) : null}
</div>
);
}
And then inside the newly-created Player component:
render() {
var pState = this.props.playerState; // Just to make this more readable
return (
<div className="player">
<PlayButton onClick={this.props.togglePlay} playing={pState.playing} />
<Timeline
currentTimeDisplay={pState.currentTimeDisplay}
setProgress={this.props.setProgress}
progress={pState.progress}
...
/>
<VolumeContainer
onMouseLeave={this.props.noShow}
setVolume={this.setVolume}
toggleMute={this.toggleMute}
...
/>
</div>
);
}
You can break the layout into as many nested components as is needed and makes sense.
Remember to actually add the onClick attribute inside the child components as well (<button onClick={this.props.onClick}>Play</button>).

Child Component in React (Meteor) not firing events

folks. I'm a relatively new Meteor developer, and after learning Blaze, I decided to start learning React, because it seemed like the right thing to do, and I sort of liked the idea of how it worked.
Anyway, I'm having issues with a bit of code I'm working on, and could use some guidance... I've got the following segments of code:
https://gist.github.com/czbaker/2101526219eea5330553
For some reason, when the form in the component is submitted, it isn't firing the function that's meant to handle submission. Instead, it refreshes the page (as event.preventDefault() never happens).
What would be causing this to happen? As per suggested on IRC, I've tried replacing onSubmit={this.handleSubmit} with the following:
onSubmit={()=>{this.handleSubmit}}
onSubmit={this.handleSubmit()}
Neither of them had any effect, the form submission function still isn't being called. I'm really confused, because I followed documentation for the most part, and it looks like it should be working.
As I'm really new to React, I'm sure I'm overlooking something, but have no idea what. Can anyone offer me some aid? Thanks in advance!
The current project is also in a BitBucket repository, for those who need it https://bitbucket.org/czbaker/karuto/
All I've been able to figure out so far is that if I render the problem component by itself (not as a child of another component) using ReactLayout, it works fine, but the second that I try to render it as a child component (doing it the way it's shown in MDG's Todos tutorial (React version), events refuse to fire, yet there's no errors.
Thanks in advance for help.
The problem is you are attempting to render the entire HTML tree using React.
If you are using flow-router and react-layout, you can simply render the document fragment that you desire and it will be placed in a designated root node which id is 'react-root'.
Otherwise, I would suggest using static-html if you don't need blaze and create a root element for React:
some_file.html:
<body>
<div id="react-container"></div>
</body>
and then render the root component into it using your preferred router.
Then, change the title dynamically via a ReactiveVar or some other method.
I am using React with React Router, alongside Google's MDL, and had the same issue (as well as a few others, such as navigating to different routes would cause a full page reload).
When attempting to find the cause, I found that removing the MDL classes from the the div surrounding {this.props.children} in my parent component resulted in the event listeners firing correctly.
After investigating, it appears that this is due to the way that MDL structures the DOM nodes, and can be resolved by either calling componentHandler.upgradeDOM() in each child component's componentDidUpdate() method, as follows:
App = React.createClass({
render() {
return(
<div className="mdl-layout mdl-js-layout">
...
<div className="mdl-layout__content">
{ this.props.children }
</div>
</div>
);
}
});
ChildComponent = React.createClass({
handleClick() {
alert("I've been clicked!");
},
render() {
return(
<div>
<button onClick={this.handleClick}
className="mdl-button mdl-js-button">Click Me</button>
</div>
);
},
componentDidUpdate() {
componentHandler.upgradeDOM();
},
});
As outlined here, http://quaintous.com/2015/07/09/react-components-with-mdl/; or by using a 'patched' version of MDL, like the one here:
https://github.com/tleunen/react-mdl
I know this is a little different to the OP's issue, but I figured I'd add this here in the hopes that it helps someone else with this issue. :)
In my Layout.jsx i changed
export default class extends React.Component {
render() {
return(
<body>
...some jsx
</body>
);
}
}
to
export default class extends React.Component {
render() {
return(
<div>
...some jsx
</div>
);
}
}
and it helps, now the React events are working fine

Pass reference of a component to another one in ReactJS

Before anyone press eagerly the close button, I already have looked the following question: ReactJS Two components communicating. My problem is exactly the third scenario developped in the current accepted answer.
I am using ReactJS to build something with two components. For HTML reasons (and presentation), i want my two components to be at two different places of the page.
For the moment, I have the following pattern, corresponding to scenario #2:
FooForm = React.createClass({
...
});
FooList = React.createClass({
...
});
FooManager = React.createClass({
...
render: function () {
return (
<div>
<FooForm ref="form" manager={this} />
<FooList ref="list" />
</div>
);
}
});
React.render(
<FooManager someProp={value} />,
document.getElementById('foo')
);
This gives something like:
<div id="foo">
<form>Form generated with the render of FooForm</form>
<ul>List generated with the render of FooList</ul>
</div>
However, i would like to have something like this:
<div id="fooform">
<form>Form generated with the render of FooForm</form>
</div>
<!-- Some HTML + other controls. Whatever I want in fact -->
<div>...</div>
<div id="foolist">
<ul>List generated with the render of FooList</ul>
</div>
The problem here is: how can I keep a reference in each component? Or at least the link Form -> List?
I tried to create the FooList before and pass the reference to the current manager, but I get the following warning/error:
Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref.
The documentation says you can attach events to link two components which do not have a parent-child relation. But I don't see how. Can someone give me some pointers?
The Less Simple Communication lesson from react-training has a good example of how you can move actions & state sideways to avoid having to create an explicit link between related components.
You don't need to jump into a full Flux implementation to get the benefit of this approach, but it's a good example to lead you up to Flux, should you eventually need it or something like it.
Note that this requires you to model the relationship between the components based on changing state rather than explicitly passing a reference to a component instance (as you're doing above) or a callback bound to the component managing the state.
This would be the perfect use-case for a Flux type architecture.
What you want is someone FooManager to be able to trigger state changes in both components. Or, in fact, having the different components trigger, through Actions, state changes in each other.
The Flux Todo-App Tutorial illustrates your use-case perfectly!
After this, then you'd have the choices of using Facebooks implementation of Flux or the other gazillion ones.
My personal favorite is Reflux

Categories

Resources