Ad

How Can I Make A Component Render OnClick In A React Functional Component?

- 1 answer

I'm a bit surprised I'm having trouble finding this online, but I can't seem to find an example of how to do this in a React functional component. I have a React component that I would like to render when I click a button. Right now the function fires and I can see my console.log firing, however the component isn't rendering. My first guess was that it won't render because React doesn't know to update the view, however I added boolean via useState and it still won't render. What am I doing wrong?

Below is the relevant code. How can I get the component in addSection to render?

const FormGroup = ({index}) => {
  const [additionalSection, setAdditionalSection] = useState(false);

  const addSection = form => {
    setAdditionalSection(true);
    console.log('form', form);

    return additionalSection && (
      <div key={form.prop}>
        <p>This should render</p>
        <AdditiveSection
          form={form}
          register={register}
          errors={errors}
        />
      </div>
    );
  };
  ...
 return (
...
 <FormAdd>
   <LinkButton
      type="button"
      onClick={() => addSection(form)}
   >
     span className="button--small">{form.button}</span>
   </LinkButton>
 </FormAdd>
);
Ad

Answer

A state change like the one you are calling, will trigger a re-render.

But all html to be rendered must be included in the functional components return statement. The elements you want to render can be conditionally rendered like this:

    const FormGroup = ({index}) => {
      const [additionalSection, setAdditionalSection] = useState(false);
    
      const addSection = form => {
        setAdditionalSection(true);
        console.log('form', form);
      };
      ...
     return (
    ...
     <FormAdd>
       <LinkButton
          type="button"
          onClick={() => addSection(form)}
       >
         <span className="button--small">{form.button}</span>
       </LinkButton>
       {additionalSection && 
         <div key={form.prop}>
            <p>This should render</p>
            <AdditiveSection
              form={form}
              register={register}
              errors={errors}
            />
          </div>
       }
     </FormAdd>
    );
Ad
source: stackoverflow.com
Ad