Here's a js fiddle showing the question in action.
In the render function of a component, I render a div with a class .blah. In the componentDidMount function of the same component, I was expecting to be able to select the class .blah and append to it like this (since the component had mounted)
$('.blah').append("<h2>Appended to Blah</h2>");
However, the appended content does not show up. I also tried (shown also in the fiddle) to append in the same way but from a parent component into a subcomponent, with the same result, and also from the subcomponent into the space of the parent component with the same result. My logic for attempting the latter was that one could be more sure that the dom element had been rendered.
At the same time, I was able (in the componentDidMount function) to getDOMNode and append to that
var domnode = this.getDOMNode();
$(domnode).append("<h2>Yeah!</h2>")
yet reasons to do with CSS styling I wished to be able to append to a div with a class that I know. Also, since according to the docs getDOMNode is deprecated, and it's not possible to use the replacement to getDOMNode to do the same thing
var reactfindDomNode = React.findDOMNode();
$(reactfindDomNode).append("<h2>doesn't work :(</h2>");
I don't think getDOMNode or findDOMNode is the correct way to do what I'm trying to do.
Question: Is it possible to append to a specific id or class in React? What approach should I use to accomplish what I'm trying to do (getDOMNode even though it's deprecated?)
var Hello = React.createClass({
componentDidMount: function(){
$('.blah').append("<h2>Appended to Blah</h2>");
$('.pokey').append("<h2>Can I append into sub component?</h2>");
var domnode = this.getDOMNode();
$(domnode).append("<h2>appended to domnode but it's actually deprecated so what do I use instead?</h2>")
var reactfindDomNode = React.findDOMNode();
$(reactfindDomNode).append("<h2>can't append to reactfindDomNode</h2>");
},
render: function() {
return (
<div class='blah'>Hi, why is the h2 not being appended here?
<SubComponent/>
</div>
)
}
});
var SubComponent = React.createClass({
componentDidMount: function(){
$('.blah').append("<h2>append to div in parent?</h2>");
},
render: function(){
return(
<div class='pokey'> Hi from Pokey, the h2 from Parent component is not appended here either?
</div>
)
}
})
React.render(<Hello name="World" />, document.getElementById('container'));
In JSX, you have to use className, not class. The console should show a warning about this.
Fixed example: https://jsfiddle.net/69z2wepo/9974/
You are using React.findDOMNode incorrectly. You have to pass a React component to it, e.g.
var node = React.findDOMNode(this);
would return the DOM node of the component itself.
However, as already mentioned, you really should avoid mutating the DOM outside React. The whole point is to describe the UI once based on the state and the props of the component. Then change the state or props to rerender the component.
Avoid using jQuery inside react, as it becomes a bit of an antipattern. I do use it a bit myself, but only for lookups/reads that are too complicated or near impossible with just react components.
Anyways, to solve your problem, can just leverage a state object:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://fb.me/react-0.13.3.js"></script>
</head>
<body>
<div id='container'></div>
<script>
'use strict';
var Hello = React.createClass({
displayName: 'Hello',
componentDidMount: function componentDidMount() {
this.setState({
blah: ['Append to blah'],
pokey: ['pokey from parent']
});
},
getInitialState: function () {
return {
blah: [],
pokey: []
};
},
appendBlah: function appendBlah(blah) {
var blahs = this.state.blah;
blahs.push(blah);
this.setState({ blah: blahs });
},
render: function render() {
var blahs = this.state.blah.map(function (b) {
return '<h2>' + b + '</h2>';
}).join('');
return React.createElement(
'div',
{ 'class': 'blah' },
{ blahs: blahs },
React.createElement(SubComponent, { pokeys: this.state.pokey, parent: this })
);
}
});
var SubComponent = React.createClass({
displayName: 'SubComponent',
componentDidMount: function componentDidMount() {
this.props.parent.appendBlah('append to div in parent?');
},
render: function render() {
var pokeys = this.props.pokeys.map(function (p) {
return '<h2>' + p + '</h2>';
}).join('');
return React.createElement(
'div',
{ 'class': 'pokey' },
{ pokeys: pokeys }
);
}
});
React.render(React.createElement(Hello, { name: 'World' }), document.getElementById('container'));
</script>
</body>
</html>
Sorry for JSX conversion, but was just easier for me to test without setting up grunt :).
Anyways, what i'm doing is leveraging the state property. When you call setState, render() is invoked again. I then leverage props to pass data down to the sub component.
Here's a version of your JSFiddle with the fewest changes I could make: JSFiddle
agmcleod's advice is right -- avoid JQuery. I would add, avoid JQuery thinking, which took me a while to figure out. In React, the render method should render what you want to see based on the state of the component. Don't manipulate the DOM after the fact, manipulate the state. When you change the state, the component will be re-rendered and you'll see the change.
Set the initial state (we haven't appended anything).
getInitialState: function () {
return {
appended: false
};
},
Change the state (we want to append)
componentDidMount: function () {
this.setState({
appended: true
});
// ...
}
Now the render function can show the extra text or not based on the state:
render: function () {
if (this.state.appended) {
appendedH2 = <h2>Appended to Blah</h2>;
} else {
appendedH2 = "";
}
return (
<div class='blah'>Hi, why isn't the h2 being appended here? {appendedH2}
<SubComponent appended={true}/> </div>
)
}
Related
I have an element that being conditionally rendered with v-if="isLogged", if a user is logged in:
<div
v-if="isLogged"
class="chatBlock"
ref="chat"
></div>
I'm trying to get scroll height of the chat reference in a mounted () function - this.$refs.logged.scrollHeight, but it's not possible, because if a user is not logged in, then this div won't be rendered on a mounting stage, so even if a user logs in - it won't work, because mounted stage already passed.
Is it possible to track element appearance in a DOM using watch method?
UPDATE
Added watcher, as Steven suggested below in a mounted ():
this.$store.watch(
(state) => {
return this.$store.getters.isLogged
},
(newValue, oldValue) => {
if (newValue) {
this.chatHeight = this.$refs.chat.scrollHeight
}
}
)
The accepted answer did not work for me. The watch does not guarantee that the element has already been rendered.
To make sure that the element is available, I had to use $nextTick
if (newValue) {
this.$nextTick(function () {
this.chatHeight = this.$refs.chat.scrollHeight
})
}
This will cause the code to be executed after the next DOM update cycle.
Add a watch to isLogged. When it is active, get your chat ref. You will also have to check on your mounted, so put your logic in a common function.
So in your component:
val componentOptions = {
methods: {
checkDiv() {
const chatDiv = this.$refs.chat
if (chatDiv) {
// your code here...
}
}
},
mounted() {
this.checkDiv();
},
watch: {
isLogged(value) {
if (value) {
this.checkDiv()
}
}
}
}
—-
You can also use v-show instead of v-if. That way your element will be rendered but hidden.
Switching to v-show, as suggested by Steven, worked for me. It was actually the better option because v-show is cheap to toggle, unlike v-if, see this answer: https://stackoverflow.com/a/44296275/2544357
I am using this plugin - bootstrap-dropselect
I have written initDropSelect function to initialize this plugin but I am not sure where to call this function as I would like to append some html to the DOM as soon as route is loaded. I am getting data from two different ajax calls. That data has to be compared and manipulated to append that html to the DOM(Code below 'Append to DOM' comment).
let UserPanel = React.createClass({
mixins: [LinkedStateMixin],
getStateFromStores: function() {
var users = UserStore.getAll();
// Some more code
return {
users: users
// Other properties
};
}
componentDidMount: function() {
UserStore.addChangeListener(this._onChange);
},
_onChange: function() {
this.setState(this.getStateFromStores());
},
initDropSelect: function() {
var _self = this;
var dropSelect = $('#dropselect-demo1').dropselect({
filter: {
show: true,
placeholder: 'Search for an item'
},
multiselect: true,
onselect: function(e, item) {
},
onunselect: function(e, item) {
},
onclear: function(e) {
}
});
// Append to DOM
if(this.state.tagsList.length > 0) {
if(this.state.newLoan.data.tags.length > 0) {
// Getting data from two different resources
}
}
}
});
Please help me in deciding where to call initDropSelect to manipulate data from multiple async requests and append that data to DOM.
P.S. I am using react router so there are two scenarios. First I may come to this route from other route or I can straightaway reload the current page.
Thanks in advance.
One way is for your render method to return something like a <div /> that you will then use to mount the jQuery component into. Once mounted, this will point to the DOM element that you would normally pass to jQuery.
Since jQuery will be handling the rendering, you then want to always return false from shouldComponentUpdate(). This will prevent React from thrashing your jQuery component.
You can then use componentDidMount() to initialize your jQuery component and componentWillReceiveProps() to update/re-render it when new data is passed in.
jQuery seems to be working fine in react component however, when I try to apply styling using jquery in react component its not working. In the below code console.log(eachVisitedTopic) within each loop is returning proper result as expected.
topicsVisited(arr){
$(function() {
$.each(arr, function(key, eachVisitedTopic) {
console.log(eachVisitedTopic);
$('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
'background-color': 'red'
});
});
});
};
Markup
import {React, ReactDOM} from '../../../../build/react';
export default class SingleTopicBox extends React.Component {
render() {
return (
<div>
<div className="col-sm-2">
<div className="single-topic" data-topic-id={this.props.topicID} onClick={() => this.props.onClick(this.props.topicID)}>
{this.props.label}
{this.props.topicID}
</div>
</div>
</div>
);
}
};
React should handle all the render, it checks the dirty dom and render only things that changed.
You can achieve what you want, just use a react state.
When you trigger a setState change react will look into the DOM and find what has changed and then render it.
Ref: https://facebook.github.io/react/docs/component-api.html#setstate
constructor() {
super();
this.state = {
bgDisplayColor: "blue"
};
}
Then you can do something like this in yout component:
$('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
'background-color': this.state.bgDisplayColor
});
And to update it you simply use:
this.setState({bgDisplayColor: "red"});
EDIT
To workaround the undefined variable error, you have to store the scope of "this" inside your function and use instead of "this", because inside the jquery .css "this" refers to Jquery and not the "this" scope of your actual class.
Example:
topicsVisited(arr){
var self = this;
$(function(){
$.each(arr, function(key, eachVisitedTopic){
console.log(eachVisitedTopic);
//self here is the global scope of your class
//Inside jQuery.css this refers to Jquery and not to your class.
$('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
'background-color': self.state.bgDisplayColor
});
});
});
});
};
Try it to by putting all jQuery code inside the componentDidMount
E.g :
componentDidMount() {
//Your jQuery function goes here
}
I have a link in a React component:
<a href="#goals-tab" className={ this.setTabStyle()}>Goals</a>
Now, inside setTabStyle method, can I access attributes of the a element, like href without explicitly passing it to the method as a parameter?
If you use a ref, then your component renders DOM without the styles, and then applies the new styles. So the user will notice the change of styles.
I would advise to pass link as a parameter to setTabStyle(link), or make the link another prop of your component:
var Component = React.createClass({
handleClick: function (e) {
console.log(e.currentTarget.getAttribute('href'));
},
setTabStyle: function () {
if (this.props.link == this.props.activelink) {
return myActiveLinkStyle
} else {
return myInactiveLinkStyle
}
},
render: function() {
return <a href={this.props.link} style={this.setTabStyle()} onClick={this.handleClick}>Click</a>;
}
});
That way, you get the right style from the initial load..
I need some help with understanding the so-called synthetic events in ReactJS. I wrote the following toy program that has a Video component and a VideoList component. When a video in the rendered list of videos is clicked, I would print out what video gets clicked in the console.
I don't understand how the event onVideoSelected() gets defined. Is it replaced by the onClick() event in the rendered Video component?
Thanks!
var Video = React.createClass({
handleClick: function() {
this.props.onVideoSelected(this.props.title);
},
render: function() {
return <li><div onClick={this.handleClick} className="bg-success">{this.props.title}</div></li>;
}
});
var VideoList = React.createClass({
propTypes: {
data: React.PropTypes.array.isRequired
},
handleVideoSelected: function(title) {
console.log('selected Video title is: ' + title);
},
render: function() {
return (
<div className="panel panel-default"><div className="panel-heading">List of Videos</div><ul>
{data.map(function (v) {
return <Video onVideoSelected={this.handleVideoSelected} key={v.title} title={v.title} />;
},this)}
</ul></div>
);
}
});
var data = [
{title: 'video title 1', link: 'http://www.youtube.com/1'},
{title: 'video title 2', link: 'http://www.youtube.com/2'},
{title: 'video title 3', link: 'http://www.youtube.com/3'}
];
React.render(<VideoList data={data} />, document.getElementById('videolist'));
There's actually no magic going on here, just passing functions around. onVideoSelected is a function reference that you passed into the Video component via a property; said another way, the flow goes like this:
What happens when you click the div? Call this.handleClick.
What happens when you call handleClick? Call this.props.onVideoSelected.
How is onVideoSelected defined? It got passed into the component, just like any other property.
What was passed in to the onVideoSelected property? A reference to the VideoList's handleVideoSelected function.
It may help to compare it to some sorta-similar, simplified jQuery code:
function handleVideoSelected(title) {
console.log('selected Video title is: ' + title);
}
function createVideoDiv(onVideoSelected, title) {
var div = $("<div className="bg-success"></div>").text(title).appendTo(...);
div.on("click", function() {
// call the function that was passed to us
onVideoSelected(title);
});
}
$.each(videos, function(idx, video) {
createVideoDiv(handleVideoSelected, video.title);
});
In the jQuery version, you pass handleVideoSelected into createVideoDiv; similarly, in the React version, you pass handleVideoSelected into Video via props.
After your onClick handler is called in the Video component you are no longer dealing with events; these are plain old function calls.
To keep a reference to the video title, pass a curried version of handleVideoSelected with the title as the first arg by using Function.prototype.bind:
{this.props.data.map(function (v) {
return <Video onVideoSelected={this.handleVideoSelected.bind(this, v.title)} key={v.title} title={v.title} />;
}, this)}
(I also prepended this.props to data. Looks like a typo in your code.)
This is how individual Todos are identified in the "Expose Component Functions" doc.