0

I have written the code with lots of if else logics. I am trying to improve my code. Can anyone suggest me some better options. I am trying to print data based on conditions: functionOne and secondFunction are the methods which will return the component at multiple places. Gist of my code is: if length of myFirstDataArray is greater than 3, than print the secondFunction value , or else, check again the length of myFirstDataArray and so on.

const functionOne = (data) => {
    return (
      <SummaryOfValues
        data={data}
      ></SummaryOfValues>
    );
  };

  const secondFunction = (data) => {
    return (
      <ListOfValues
        data={data.info}
      ></ListOfValues>
    );
  };

{
  myFirstDataArray && myFirstDataArray.length >= 3 ? (
    <>
      <>
        {resultedDataArray
          .slice(0, 3)
          .map((data: any) => ({ secondFunction(data); }))}
      </>
    </>
  ) : (
    <>
      <>
        {resultedDataArray
          .slice(0, resultedDataArray.length)
          .map((data: any) => ({ secondFunction(data); }))}
      </>

      {myFirstDataArray && myFirstDataArray.length === 1 ? (
        <>
          {resultedDataArray
            .slice(myFirstDataArray.length)
            .map((data: any) => ({ functionOne(data); }))}
        </>
      ) : null}
      {myFirstDataArray && myFirstDataArray.length === 2 ? (
        <>
          {resultedDataArray
            .slice(myFirstDataArray.length, myFirstDataArray.length + 1)
            .map((data: any) => ({ functionOne(data); }))}
        </>
      ) : null}
    </>
  );
}

1 Answer 1

1

How do you think of this solution?

const functionOne = (data) => {
    return (
        <SummaryOfValues
            data={data}
        ></SummaryOfValues>
    );
};

const secondFunction = (data) => {
    return (
        <ListOfValues
            data={data.info}
        ></ListOfValues>
    );
};

{
    myFirstDataArray && myFirstDataArray.length > 0 (
        <>
            <>
                {resultedDataArray
                    .slice(0, 3)
                    .map((data: any) => ({ secondFunction(data); }))}
            </>
            {myFirstDataArray.length < 3 ? (
                <>
                    {resultedDataArray
                        .slice(myFirstDataArray.length - 1)
                        .map((data: any) => ({ functionOne(data); }))}
                </>
            ) : null}
            </>
        );
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am looking forward to remove as much as conditional rendering I can remove.
I've updated the code. Please let me know how you think of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.