Roman Nozhenko
Roman Nozhenko

Reputation: 628

Twinkling images in a component

I have component with navigation, on click item to child component passed in props some params, one of params - object 'itemImage' with className and url, like this:

{
    url: '/static/image.svg',
    className: 'absolute hidden md:block min-w-53 lg:min-w-68 mt-30 lg:mt-19 -ml-28 lg:-ml-75',
}

In child component ItemComponent:

{
     itemImage &&
     <img className={itemImage.className} src={itemImage.url} alt='' />
}

ItemComponent is selected from an array according to the order of the element in navigation (it is responsible for the object passed to the child component), since the list of navigation elements and elements of the array of pictures are not related and of different lengths. The sample is implemented on the basis of an index in map for objects and an index in an array with pictures, to be more precise.

Problem:
the pictures flicker as the state of the parent and the child is updated, is it possible to somehow avoid this and make the change of the picture clear without the flickering of the previous card.

Upvotes: 0

Views: 267

Answers (2)

Dhaval Patel
Dhaval Patel

Reputation: 7601

You can use the below-mentioned code to render the Array of Images.

  <>
            {this.props.Images.map(item=>{
                return (item)
            })}
             <p>
               {JSON.stringify(this.state)}
            </p>
            <p>
               {JSON.stringify(this.props.changed)}
            </p>
            <button onClick={this.props.onChange}>Change</button>
            <button onClick={this.onCurrentChange}>Current State Change</button>
        </>

Please check the demo here Demo

Upvotes: 1

Felipe Toffolo
Felipe Toffolo

Reputation: 1

You can make somethings to try to prevent that.

1- Add a key prop to the elements. It help react understand that it is the same data from before and not re-render that piece.

2- Use react PureComponent on the flickering element https://reactjs.org/docs/react-api.html#reactpurecomponent to prevent the re-render

3 - Instead of purecomponent implement shouldComponentUpdate

Upvotes: 0

Related Questions