I have this line of code
render() {
return <img class="animated bounceIn" src={this.state.img_source}></img>
}
Animation is played. When I change img_source by setState(), react detects changes only at source of the image, and changes the picture. So animation is not played again.
How can I make animation played again?
First, you have to use "className", not "class" in react JSX. Next, be pragmatic: animation is probably triggered by css and render is redrawn every time you change the state.
export class MyComponent extends React.Component {
//... code
render() {
return (
<img
className={this.state.className}
src={this.state.img_source}
></img>)
}
It's enough to manage class names in state and them will be applied to your render automagically with the same effects that you would get with other well known libraries as jQuery.
You can use the React component lifecycle methods.
componentDidUpdate will serve the purpose.
componentDidUpdate (prevProps, prevState) {
if (prevState.img_source !== this.state.img_source) {
// Redo the animation
}
}
Since the animation is triggered by css, then you must remove and add the classes when updating the state of the img src:
render() {
return <img ref={i => {this.img = i}} className={"animated bounceIn"} src={this.state.img_source}></img>
}
componentDidUpdate (pps, pst) {
if (prevState.img_source !== this.state.img_source) {
this.img.classList.remove("animated");
this.img.classList.remove("bounceIn");
this.img.classList.add("animated");
this.img.classList.add("bounceIn");
}
}
Using ref you can reference the Dom element and add / remove de classes manually. It's not elegant but it works
Related
I'm new to React JS coding...
I would like to know any method to be called in Class-Based Components whenever it gets props and called by another component in their render return methods.
Actually! I wanted to run that function every time when that component is being Rendered or Called By another component.
I appreciate that...
In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.
This is why in React classes, we put side effects into componentDidMount and componentDidUpdate. Coming back to our example, here is a React counter class component that updates the document title right after React makes changes to the DOM:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
we have to duplicate the code between these two lifecycle methods in Classes.
This is because in many cases we want to perform the same side effect regardless of whether the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render — but React class components don’t have a method like this. We could extract a separate method but we would still have to call it in two places.
I wish to show a modal dialog box (such as an alert()) every time a Meteor subscription, tracked in React with withTracker, changes.
I have tried using Tracker.autorun to track changes but cannot work out where in the code to place it. It does not seem to work in the Component constructor and runs every time if placed in render().
This is an outline of what my code looks like:
class Foo extends Component {
render() {
return (
<h1>Example Header</h1>
{ this.maybeShowAlert() }
);
}
maybeShowAlert() {
// ONLY if bar has been updated
alert('bar has changed');
}
}
export default withTracker(() => {
Meteor.subscribe('bar')
return {
bar: Bar.findOne({})
};
})(Foo);
Haven't used Meteor before, but if you want to do things in response to state/prop changes then componentDidUpdate() is the lifecycle method for it. E.g.
componentDidUpdate(prevProps) {
if (this.props.bar !== prevProps.bar {
// bar prop has changed
alert("bar changed);
}
}
If you're going to use Tracker.autorun, then the best place to call that is in componentDidMount, because it's called only once after the component has been mounted. You only need to call the tracker function once since the tracker function will rerun whenever the reactive data sources that it depends on ever changes. In the tracker function is where you will call maybeShowAlert depending on the value of bar like so,
componentDidMount() {
Tracker.autorun(() => {
let bar = this.props.bar;
if (bar) {
this.maybeShowAlert();
}
}
}
I am trying to make this component move in when mounted but getting
Cannot read property 'enter' of undefined
Here is a simplified code (I have all the CSS classes ready):
class Example extends React.Component {
state = {
transitionIn: false,
};
componentDidMount = () => {
this.setState({ transitionIn: true })
}
render() {
return (
<CSSTransition
in={this.state.transitionIn}
timeout={1000}
className={'wordTransition'}
>
<div>dksjfnsdkjnfj</div>
</CSSTransition>
);
}
}
https://codesandbox.io/s/rj5046zxoo
I believe that the error you were experiencing is one that you solved in the codesandbox.io link you provided above. I was having this same problem. Instead of naming the prop that takes a class name to be used as the prefix for the various transition states classNames (plural) I was using the more familiar className (singular).
To reiterate: inside the <CSSTransition> component, make sure you are using a classNames prop and not className as you would inside of a react component's html elements.
I feel that the choice on the part of the React Transition Group to use a prop called classNames in their component is confusing and should perhaps be reconsidered.
I am trying to force a child component to re-render. I have tried this.forceUpdate();, but it does not work. I put console.log statements in my <PostList /> component, and none of them are ever called--not componentDidMount, nor componentWillMount, componentWillReceiveProps, none of them. It's as if the <PostList /> component is never initialized. I am sure it is though, because I know for a fact items.count retrieves my items. Here is my render method:
render() {
const items = this.state.posts;
const postList = items.count > 0 ? (<PostList comingFromSearch={true} xyz={items} />) : (<div></div>)
const navBar = <NavigationBar />
return (
<div><br/>{navBar}
<div className="container">
<h3>Search Results for {this.state.searchTerm}</h3>
<div className="row">
<div className="col-x-12">{postList}</div>
</div>
</div>
</div>
)
}
And here is my api call:
retrieveSearch(term) {
Helpers.searchWithTerm(term).then((terms) => {
const postsWithTermsInTitle = terms.titleResults
this.setState({posts: postsWithTermsInTitle})
this.forceUpdate();
}).catch((error) => {
console.log("error searching: " + error);
})
}
I should note, on my previous page, i had another ` component, and maybe react is using that one instead of this one? I want to force it to use this instance.
If this.forceUpdate(); does not make the whole DOM re-render, how can I do that?
thanks
your PostList and NavigationBar Components might not update because they only update when their props are changed (shallow compare).
PostList might not update when changing the inner content of the array, because the component will shallow compare the new state with the previous one. Shallow comparing an array will basically checked against its length property. which does not change in this case.
Quick Solution
Sometimes you need to update a List, without changing any of its props or the length of the list. To achieve this, just pass a prop to the component and keep incrementing it instead of calling force update.
retrieveSearch(term) {
Helpers.searchWithTerm(term).then((terms) => {
const postsWithTermsInTitle = terms.titleResults
this.setState((curState) => ({posts: postsWithTermsInTitle, refreshCycle: curState.refreshCycle+1}))
this.forceUpdate();
}).catch((error) => {
console.log("error searching: " + error);
})
}
render() {
...
<PostList
...
refreshCycle={this.state.refreshCycle}
/>
...
}
Right solution
The right solution is to provide an itemRenderer which you is a function that returns the an individual item from the list. This function is passed as a prop to the component.
This way you have control over how the items inside the list will appear, also changes inside the itemRenderer function will cause a component update.
itemRenderer(itemIndex) {
return <div>{this.props.item[itemIndex]}</div>;
}
render() {
...
<PostList
itemRenderer={this.itemRenderer.bind(this)}
itemsLength={items.length}
/>
...
}
The itemRenderer will be called inside the PostList in a loop (of length itemsLength). each loop will be passed the index of the current iteration, so you can know which item of the list to return from the function.
This way you can also make your list more scalable and more accommodating.
You can check an implementation of such solution on a list package like this one: https://www.npmjs.com/package/react-list
You can force a re-render of a component and all its children by changing the state of the component. In the constructor add a state object:
constructor(props) {
super(props)
this.state = {
someComponentState: 'someValue'
}
}
Now whenever you do:
this.setState(someComponentState, 'newValue')
It will re-render the component and all its children.
This of course assumes your component is a class based component, not a functional component. However, if your component is a functional component you can easily transform it to a class based component as follows:
class ComponentName {
constructor() {
// constructor code
}
render() {
// render code
}
}
export default ComponentName
Understand that componenet level state is not the same as redux state but is exposed only inside the component itself.
I would like to set the state of a component based on the current size of the browser window. The server-side rendering has been used (React+Redux). I was thinking about using the Redux store as a glue - just to update the store on resize.
Is there any other/better solution that doesn't involve Redux.
Thanks.
class FocalImage extends Component {
// won't work - the backend rendering is used
// componentDidMount() {
// window.addEventListener(...);
//}
//componentWillUnmount() {
// window.removeEventListener('resize' ....);
//}
onresize(e) {
//
}
render() {
const {src, className, nativeWidth, nativeHeight} = this.props;
return (
<div className={cn(className, s.focalImage)}>
<div className={s.imageWrapper}>
<img src={src} className={_compare_ratios_ ? s.tall : s.wide}/>
</div>
</div>
);
}
}
I have a resize helper component that I can pass a function to, which looks like this:
class ResizeHelper extends React.Component {
static propTypes = {
onWindowResize: PropTypes.func,
};
constructor() {
super();
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
if (this.props.onWindowResize) {
window.addEventListener('resize', this.handleResize);
}
}
componentWillUnmount() {
if (this.props.onWindowResize) {
window.removeEventListener('resize', this.handleResize);
}
}
handleResize(event) {
if ('function' === typeof this.props.onWindowResize) {
// we want this to fire immediately the first time but wait to fire again
// that way when you hit a break it happens fast and only lags if you hit another break immediately
if (!this.resizeTimer) {
this.props.onWindowResize(event);
this.resizeTimer = setTimeout(() => {
this.resizeTimer = false;
}, 250); // this debounce rate could be passed as a prop
}
}
}
render() {
return (<div />);
}
}
Then any component that needs to do something on resize can use it like this:
<ResizeHelper onWindowResize={this.handleResize} />
You also may need to call the passed function once on componentDidMount to set up the UI. Since componentDidMount and componentWillUnmount never get called on the server this works perfectly in my isomorphic App.
My solution is to handle resize event on the top-most level and pass it down to my top-most component, you can see full code here, but the gist is:
let prevBrowserWidth
//re-renders only if container size changed, good place to debounce
let renderApp = function() {
const browserWidth = window.document.body.offsetWidth
//saves re-render if nothing changed
if (browserWidth === prevBrowserWidth) {
return
}
prevBrowserWidth = browserWidth
render(<App browserWidth={browserWidth} />, document.getElementById('root'))
}
//subscribing to resize event
window.addEventListener('resize', renderApp)
It obviously works without Redux (while I still use Redux) and I figured it would be as easy to do same with Redux. The advantage of this solution, compared to one with a component is that your react components stay completely agnostic of this and work with browser width as with any other props passed down. So it's a localized place to handle a side-effect. The disadvantage is that it only gives you a property and not event itself, so you can't really rely on it to trigger something that is outside of render function.
Besides that you can workaround you server-side rendering issue by using something like:
import ExecutionEnvironment from 'exenv'
//...
componentWillMount() {
if (ExecutionEnvironment.canUseDOM) {
window.addEventListener(...);
}
}