How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png

let finalSplit = [
    {
      start: "73",
      end: "76",
      splits: [
        {
          word: "Now",
          start: "73",
          color:"#FF6262",
          name:"extra",
          end: "76",
        },
      ],
    },
    {
      start: "27",
      end: "72",
      splits: [
        {
          word: "GitHub Actions",
          start: "31",
          name:"sub1",
          color:"#DFF652",
          end: "45",
        },
        {
          word: "the GitHub Actions “New Workflow” experience.",
          start: "27",
          name:"main",
          color:"#62FF8E",
          end: "72",
        },
        {
          word: "GitHub",
          start: "31",
          name:"sub2",
          color:"#9483FF",
          end: "37",
        },
      ],
    },
  ];
  

I attempted to render each array in a loop but encountered duplicates, preventing me from rendering it in an aggregated form.

const Mark = () => {
    
    return (
        <>
        {
            finalSplit.map((i)=>{
                return (
                    <div>
                        i.split.map((j)=>{
                            <div>{j.text}</div>
                        })
                    </div>
                )
            })
        }
        <>
    );
}

I need to generate another structure with text: "announcing improvements to the GitHub Actions “New Workflow” experience. Now, when you want to create" along with their respective offsets.

Answer №1

This particular solution is effective to a certain extent utilizing the concepts of sorting and absolute positioning. When actual pixel position values are provided, it can produce results similar to the image you have shared.

const Mark = () => {
  const sortData = (data) => {
    return data.sort((a, b) => {
      if (a.start === b.start) {
        return b.end - a.end;
      } else {
        return a.start - b.start;
      }
    });
  };

  const sortNestedData = (data) => {
    const unsortedData = data.map((item) => {
      if (item?.splits) {
        return { ...item, splits: sortNestedData(item.splits) };
      }
      return item;
    });
    return sortData(unsortedData);
  };

  const renderNestedData = (data) => {
    const myData = data.map((item) => {
      return (
        <div
          style={{
            backgroundColor: item.color,
            position: "absolute",
            left: `${item.start}px`,
            // width: `${item.end - item.start}px`,
            top: "0px"
          }}
        >
          {item.word}
          {item.splits && renderNestedData(item.splits)}
        </div>
      );
    });
    return myData;
  };

  return (
    <div
      style={{
        backgroundColor: "lightblue",
        display: "flex",
        flexDirection: "row",
        position: "absolute"
      }}
    >
      {renderNestedData(sortNestedData(finalSplit))}
    </div>
  );
};

export default Mark;

Code playground => https://codesandbox.io/s/festive-violet-cc8s7?file=/src/App.js

https://i.stack.imgur.com/IPJG6.png

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

What steps should I follow to create a large Angular single page application using ASP.NET MVC?

After gaining some experience with AngularJS on a small project, I am now ready to tackle a larger application. My plan is to create a single-page application using asp.net, making WebAPI calls and loading AngularJS views. However, I am unsure about how ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

The content contained within the .each loop within the click event is only executed a single time

While working on coding a menu opening animation, I encountered an issue today. Upon clicking the menu button, the menu opens and the elements inside receive an added class (resulting in a fade-in effect). Clicking the menu button again should close the ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Exploring the Depths of Vue Router: Incorporating Dynamic Nested Routes

Hey everyone, I'm currently diving into working with the vue-router and Vuex Store. I'm facing a challenge where I have a route that consists of two dynamic parameters (:id, :templateId). My question is, what do I need to specify in my routes c ...

Is JavaScript the Key to Navigating Through a Website?

I am faced with the challenge of creating a script to extract a database from a website. The website's main page features a table where each row contains a link to another page that holds the desired database. Currently, my script can successfully e ...

Express along with Cheerio and JSDOM

I'm currently exploring the integration of Cheerio with Express to enable server-side DOM manipulation. I haven't had much luck beyond basic web scraping techniques. There are specific requirements I need to meet for this project. Currently, I ...

Launch a Next.JS web application utilizing Yarn on Google App Engine

I'm in the process of deploying a web application that was constructed using templates provided by a friend. I don't have much experience with React/NextJS frameworks, so I'm uncertain about the distinctions between yarn and npx. When runni ...

utilize ng-bind to apply numerous values simultaneously

Is it possible to bind multiple values using ng-bind in the following manner : <p ng-bind="instructor.first_name instructor.last_name"></p> Every time I attempt this, I encounter the following error: Error: $parse:syntax Syntax Error I am a ...

Instructions on converting a SQL expression to Sequelize

Could someone assist with converting this to sequelize? CREATE TABLE "fundraiserUpdates" ( "updateId" SERIAL, "updateFundraiserId" INTEGER NOT NULL, "updateTitle" TEXT NOT NULL, "updateDescription" TEXT NOT NULL, CONSTRAINT "pk_fundraiser ...

Store various dropdown selections in an array

Questions are being generated from a database for users to answer using a drop-down menu. Upon selecting a specific option, a suggestion is added to an array triggering a JavaScript on-change event. Once all questions are answered, the array including all ...

how can I pass a group of values as an argument in math.sum function?

Using math.js for convenience, I was intrigued if I could utilize the math.sum method to calculate the sum of a collection of input values. For example, something along the lines of: Here's a snippet of code to help visualize my concept: $(documen ...

A guide on invoking an onclick function within a Template literal in React.js

I am seeking assistance with implementing an on-click function using template literals in React JS. When a button within the template literal is clicked, I want to trigger another function in React JS. addPopupToLayer = (surface, layer) => { cons ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

Is it possible to use JavaScript to forcefully transition a CSS keyframe animation to its end state?

One dilemma I am facing involves CSS keyframe animations triggered by scroll behavior. When users scroll too quickly, I would like JavaScript to help send some of the animations to their 'finished/final' state, especially since the animations bui ...

Using Rails and Haml to Implement Smooth Scrolling with Jquery and CoffeeScript

Looking to accomplish a straightforward task using CoffeeScript, Rails, and Haml. While I don't have much experience with CoffeeScript, I'm eager to experiment. The goal is to have the view scroll to a specific div id when a button is pressed. A ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

The element is absent in Type {}, however, it is mandatory in Type '&' and '&' cannot be designated to String Index Type Errors

I have a goal of passing the logged-in user's email address to a 'dict' as a key, fetching its corresponding token value, and using it as a query parameter for an API call. The user's email is retrieved from the user data upon login, sp ...

Can you explain the distinction between using single and double quotes in my JavaScript and CSS code?

Is there a significant distinction between using single or double quotes in JS and CSS? Does it depend on personal preference, or are there certain instances where one is preferred over the other? In W3Schools, they employ single quotes for url('&apo ...

Unattractive destructuring during conditional assignment

When working with object properties, ESLint often suggests using object destructuring. However, this can sometimes result in redundant lines of code. ESLint may not allow something like the following (which might seem like the preferable approach): const ...