What factors does React consider when deciding between replacing or updating a component?

This particular snippet of code showcases a function called Baz:

function Baz({on}) {
  const rect1 = <rect x='10' y='10' fill='red' width='10' height='10' />
  const rect2 = <rect x='80' y='10' fill='red' width='10' height='10' />
  const Rect3 = () => <rect x='10' y='80' fill='red' width='10' height='10' />
  const Rect4 = () => <rect x='80' y='80' fill='red' width='10' height='10' />
  return (
    <svg viewBox="0 0 100 100">
      { on ? rect1 : rect2 }
      { on ? <Rect3 /> : <Rect4 /> }
    </svg>
  );
}

One interesting behavior here is that the transition from rect1 to rect2 will animate (if css transitions are enabled), while the transition from Rect3 to Rect4 won't.

The question arises: Why does this happen, and are there any potential workarounds?

To better understand this concept, feel free to check out this interactive example on jsfiddle: https://jsfiddle.net/2jLtn39z/

Answer №1

It seems like the initial update happens when you make modifications to the jsx elements in the first scenario, while in the second scenario, the component gets swapped out for a different one.

Answer №2

After receiving some great advice, I was able to find a solution that worked for me. By changing the <Rect3 /> element (which mounts Rect3 as a Component) to { Rect3() } (which returns the JSX elements and inserts them into the parent component without creating new components), I was able to make the animation work smoothly. This technique also applies to SVGs imported as ReactComponents, but keep in mind that if the imported SVG is a class-component rather than a functional component, you will need to call its render method instead.

If you're interested, here's an updated fiddle with the solution: https://jsfiddle.net/Ld6e0zyj/

const useState = React.useState
function Svg() {
  const [on, setOn] = useState(true);
  const toggle = () => setOn(on => !on);
  const rect1 = <rect x='10' y='10' fill='red' width='10' height='10' />;
  const rect2 = <rect x='80' y='10' fill='red' width='10' height='10' />;
  const Rect3 = () => <rect x='10' y='80' fill='red' width='10' height='10' />;
  class Rect4 extends React.Component {
    render() {
      return <rect x='80' y='80' fill='red' width='10' height='10' />;
    }
  }
  return (
    <div>
      <svg viewBox="0 0 100 100">
        { on ? rect1 : rect2 }
        { on ? Rect3() : new Rect4().render() }
      </svg>
      <button onClick={toggle}> Toggle </button>
    </div>
  );
}
ReactDOM.render(<Svg />, document.querySelector("#app"))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to execute application due to invalid element type

I'm just diving into learning React Native, and as I attempt to launch my app, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Verif ...

The Component received an undefined state

One of my components was originally a class component, structured like this: interface MyState { x_data: number[] y_data: number[] order_graph_1: number } class ItemsContainerOld extends React.Component<MyProps, MyState> { constructor(props: ...

Is it possible to modify the source code of WSO2 DevPortal and Publisher for customization purposes?

After downloading the source code for WSO2 API Manager, I realized that there are no .jsx files to customize. Although I am aware of how to customize the devportal and publisher, my intention is to work directly on the source code itself. What could be c ...

Is it possible to add animation to an SVG filter to create a captivating rotating planet with color effects?

I've added a filter to my self-created SVG and I'm interested in animating it so that the colors move diagonally, giving the appearance of a spinning planet. Below is the code featuring my SVG and how I'd like it to begin with the blue colo ...

Determine the div's width inside the viewport

I am trying to determine the width of a div within the viewport. When using .css(width) on my div, it calculates the overall width instead. Here is the code I am currently using: var $Windowwidth = $(window).width(); var $lefty = $("#gallerytop"); var $G ...

Custom configuration for loading static images using Webpack file loader

Hello, I have a folder named /images which has a sub-directory called /static containing various images. I am wondering how I can configure webpack to make these images from the images/static path publicly available at dist/images/image-name.png, while k ...

What could be causing Facebook to scramble my webpage links?

When I insert the link to specific pages on my website into a Facebook post, something strange happens. The original URL looks like this: http://myhymnal.net/2/be-thou-my-vision However, when I paste it into Facebook, the URL that gets fetched ends up lo ...

Adjusting the date to be one month earlier

I'm currently implementing a Reactjs DatePicker and I want to set the startDate function to one month prior to today's date. Here is my code snippet: import React, { Component } from "react"; import DatePicker from "react-date-picker"; class D ...

Getting star ratings from the "rating" field in an array of objects using JavaScript

I am dealing with an array of objects that looks like this: var test_data = [ { "id" : "Test01", //Must be a string form ID "test_info" : "This is the test information", "tes ...

The Heroku application running with Express React Server-Side Rendering has experienced a crash

I'm currently attempting to deploy my basic node application on the Heroku platform. Below is the server.js file, which serves as the entry point: require('babel-register') const express = require('express') const React = requi ...

Styling Material-UI Icons in React Using Style Mapping

What is the most efficient way to apply the same style to multiple material-ui icon elements without individually styling each object? const btns = [ { name: "test1", icon: <Icon1 />, link: "test1" }, { name: "test2", icon: <Icon2 />, li ...

Utilizing Material-UI select fields to dynamically render lists based on the values that have been selected

I am working with a material-ui component called SelectField which is filled with MenuItems. My goal is to select one of the values from the SelectField and have it displayed in a list that appears below the field. Can someone guide me on how to get start ...

How can I achieve this particular design using flexbox?

Check out the image here: . I'm struggling to understand the examples and live flex configurators. Are they only showing simple examples, or am I just not grasping it? Is it possible for me to use media queries to hide a4 when the screen is less than ...

When combining React and ReactDOM with browserify, the resulting bundle size exceeds that of react.min.js and react-dom.min.js

I'm currently working through the React beginner's tutorial and things are going smoothly so far. However, I decided to delve into importing external packages and began using tools like npm, browserify, watchify, etc. In the tutorial, there is a ...

Adjusting the heights of all elements with identical ids simultaneously

I found the following code: <div xmlns="http://www.w3.org/1999/xhtml" style="z-index: 1; position: absolute; top: 90px; left: 90px; background: none repeat scroll 0% 0% black; width: 800px;" id="mainDiv"> <div style="width: 405px;" class= ...

Determining the type of a form element by identifying the select using its name attribute

<FORM NAME="form1" METHOD="POST" ACTION="survey.php"> <p>q2: Who is your closest friend?</P> <select name='q2' id='q21'> <option value='0'>Select a Name</option> < ...

Implementing a React app mounting functionality upon clicking an HTML button

Is there a way to mount a react application by clicking on a standard html button outside of the application itself? My index.html layout is as follows: <div id="app"></div> <button id="button-root">Live chat</butt ...

Replace the text enclosed within a span tag that does not have an identifier using JavaScript

There is a span element without an id in my code For example: <span>Welcome</span> I have multiple span elements on the same webpage. Is there a method to target this specific span element using JavaScript and modify the content from "Welcom ...

Create a form based on a bootstrap table row

this is my sample. I want to implement a feature where clicking on a row will display a form at the bottom of the page for user correction. I have used jquery .html() to render the lower table, but I'm unsure how to set up an input form for it. this ...

What is the best way to highlight Navbar links when reaching a specific section?

When designing my website, I encountered an issue with the active navigation link style. It successfully changes when clicked and scrolled to the section, but does not update when the user scrolls away. How can I make the active style update on user scroll ...