reactjstypescriptreact-typescriptrecursive-datastructuresrecursive-type

how can I create a component where I can add as many levels of subpoints I can recursively in a react component


Earlier my component had only one level of subpoint so,

it would look like

main point 1

main point 2

For this my code looked like this

    interface PointCardProps {
    pointData: {
      mainPoint: string
      subPoint: string[]
    }[] 
  }

export const singleNest = (props:PointCardProps) => {
    return(
        <ol>
        {props.pointData.map((value) => {
          return (
            <>
              <li>
                <div>
                  {value.mainPoint}
                  <div>
                    <ul>
                      {value.subPoint.map((point) => {
                        return <li>{point}</li>
                      })}
                    </ul>
                  </div>
                </div>
              </li>
            </>
          )
        })}
      </ol>
    )
}

How can I change the component in such a way that it can have any amount of levels

eg: main point 1

need to start with changing interface, please help


Solution

  • Here you have recursive react component with recursive props:

    type Point = {
      point: string;
      subpoints: Point[];
    };
    
    const points = {
      point: "0",
      subpoints: [
        {
          point: "1",
          subpoints: [
            {
              point: "2",
              subpoints: []
            }
          ]
        }
      ]
    };
    
    const RecursiveList = (props: Point) => {
      const { point, subpoints } = props;
      console.log({ subpoints });
    
      return (
        <>
          <div>{point}</div>
          <ul>
            {subpoints.map((elem, index) => (
              <RecursiveList key={index} {...elem} />
            ))}
          </ul>
        </>
      );
    };
    
    export default function App() {
      return <RecursiveList {...points} />;
    }