Home > Software design >  How can I make a component render onClick in a React functional component?
How can I make a component render onClick in a React functional component?

Time:04-01

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>
);

CodePudding user response:

You should change your state (or a prop in your useEffect dependency array in case you had one) in order to force a rerender. In this case:

setAdditionalSection(prevState=>!prevState);

CodePudding user response:

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>
    );
  • Related