skip to Main Content

I have three components . First one FormTemplate in which children come as a props.FormRender which have two props FormTemplate ,formSection.I am trying to put formSection inside FormTemplate. but it is not working

current output

Form Template
Form Template End
section

Expected output

Form Template 
section
Form Template End

can you please help how to achieve this

here is my code
https://codesandbox.io/s/elegant-elbakyan-j429zl?file=/src/App.js:0-505

import "./styles.css";

function FormTemplate({ children }) {
  return (
    <>
      <div>Form Template</div>
      <div>{children}</div>
      <div>Form Template End</div>
    </>
  );
}

function FormRender({ formTemplate, formSection }) {
  return (
    <>
      {formTemplate}
      {formSection}
    </>
  );
}

export default function App() {
  return (
    <div>
      <FormRender
        formTemplate={<FormTemplate />}
        formSection={<section>section</section>}
      />
    </div>
  );
}

2

Answers


  1. You can instead pass the component definition:

    formTemplate={FormTemplate}
    

    then, within your renderer, use the component as JSX. You need to ensure you give the component a capital letter so that React sees it as a custom component, which I’ve done below by destructuring and providing a new variable name (: FormTemplateComponent):

    function FormRender({ formTemplate: FormTemplateComponent, formSection }) {
      return (
        <FormTemplateComponent>
          {formSection}
        </FormTemplateComponent>
      );
    }
    
    Login or Signup to reply.
  2. Render the formSection component as a child inside the FormTemplateComponent.

    function FormRender({ formTemplate: FormTemplateComponent, formSection }) {
      return (
        <div>
          <FormTemplateComponent>
            {formSection}
          </FormTemplateComponent>
        </div>
      );
    }
    

    Putting it together in the entire App:

    import React from "react";
    import "./styles.css";
    
    function FormTemplate({ children }) {
      return (
        <>
          <div>Form Template</div>
          <div>{children}</div>
          <div>Form Template End</div>
        </>
      );
    }
    
    function FormRender({ formTemplate: FormTemplateComponent, formSection }) {
      return (
        <div>
          <FormTemplateComponent>
            {formSection}
          </FormTemplateComponent>
        </div>
      );
    }
    
    export default function App() {
      return (
        <div>
          <FormRender
            formTemplate={FormTemplate}
            formSection={<section>section</section>}
          />
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search