Home > database >  How can I have conditional buttons without repeating code. React
How can I have conditional buttons without repeating code. React

Time:10-29

I am trying to make it so the buttons are only visible in my create page. I have figured out how to do this although in such a way that code is repeated

if (mode != "view") {

  return (
    <>
      <section
        className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
      >
        <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
        <div className="col-12"></div>
        {sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput={input}
            formData={formData}
            setFormData={setFormData}
            options={options}
            mode={mode}
            staticVars={staticVars}
            SetStaticVars={SetStaticVars}
            i={i}
            idx={idx}
            arrayLength={arrayLength}
            sectionUID={sectionInputArray.UID}
          />
        ))} 

        {/* Button to add new field */}
        <button
          id ="TestButton1"
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            // console.log(`${sectionInputArray.name} section will be added`);
            // console.log({ formDataTarget: formData[sectionInputArray.UID] });

            // New Inbound Rule
            // console.log([
            //   ...formData[sectionInputArray.UID],
            //   NestedListIDSingle(sectionInputArray),
            // ]);

            let addedFormData = {
              ...formData,
              [`${sectionInputArray.UID}`]: [
                ...formData[sectionInputArray.UID],
                NestedListIDSingle(sectionInputArray),
              ],
            };

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z] /g, "")
              .substr(0, 11);

            let withRandom = {
              ...addedFormData,
              rand_value: randomVal,
            };

            // console.log({ addedFormData: addedFormData });

            setFormData(withRandom);
          }}
        >
          Add New {sectionInputArray.name}
        </button>

        {/* Button to remove section (or created form) */}
        <button
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            console.log(
              `${sectionInputArray.name}-${idx} section will be removed`
            );
            // formData[sectionInputArray.UID].splice(idx, 1);

            let formDataTarget = formData[sectionInputArray.UID];
            // console.log(formDataTarget);

            let newFD = formData;

            newFD[sectionInputArray.UID].splice(idx, 1);

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z] /g, "")
              .substr(0, 11);

            let withRandom = {
              ...newFD,
              rand_value: randomVal,
            };

            setFormData(withRandom);
          }}
        >
          Remove {sectionInputArray.name}
        </button>

      </section>
      </>
      
      );
    } else {
      return (

        <>
      <section
        className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
      >
        <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
        <div className="col-12"></div>
        {sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput={input}
            formData={formData}
            setFormData={setFormData}
            options={options}
            mode={mode}
            staticVars={staticVars}
            SetStaticVars={SetStaticVars}
            i={i}
            idx={idx}
            arrayLength={arrayLength}
            sectionUID={sectionInputArray.UID}
          />
        ))} 
        
        </section>
        </>
        
      )

As you can see above when it is not on the view page it will then not use the buttons as it is removed within the 'else' section.

How could i create an instance of this, when the button is conditional. I tried placing an if statement just before the button section however that did not work

CodePudding user response:

Yes you can do it - place your conditional rendering (operator &&) after your <NestedDynamicInputCreation

return (
  <>
    <section
      className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
    >
      <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
      <div className="col-12"></div>
      {sectionInputArray.contents.map((input, i) => (
        <NestedDynamicInputCreation
          singleInput={input}
          formData={formData}
          setFormData={setFormData}
          options={options}
          mode={mode}
          staticVars={staticVars}
          SetStaticVars={SetStaticVars}
          i={i}
          idx={idx}
          arrayLength={arrayLength}
          sectionUID={sectionInputArray.UID}
        />
      ))} 
      {mode != 'view' && (
        <>
          <button
            id ="TestButton1"
            className="btn btn-primary bt-btn m-3"
            type="button"
            onClick={() => {
              ...
            })
          >
            Add New {sectionInputArray.name}
          </button>
          <button
            className="btn btn-primary bt-btn m-3"
            type="button"
            onClick={() => {
              ..
            })
          >
            Remove {sectionInputArray.name}
          </button>
        </>
      )}
    </section>
  </>
);

CodePudding user response:

If the content the same you could use Fragments and conditionally show the buttons:

  return (
    <>
      <section
        className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
      >
        <h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
        <div className="col-12"></div>
        {sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput={input}
            formData={formData}
            setFormData={setFormData}
            options={options}
            mode={mode}
            staticVars={staticVars}
            SetStaticVars={SetStaticVars}
            i={i}
            idx={idx}
            arrayLength={arrayLength}
            sectionUID={sectionInputArray.UID}
          />
        ))} 
        {mode !== 'view' && (
        <>
                   <button
          id ="TestButton1"
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            // console.log(`${sectionInputArray.name} section will be added`);
            // console.log({ formDataTarget: formData[sectionInputArray.UID] });

            // New Inbound Rule
            // console.log([
            //   ...formData[sectionInputArray.UID],
            //   NestedListIDSingle(sectionInputArray),
            // ]);

            let addedFormData = {
              ...formData,
              [`${sectionInputArray.UID}`]: [
                ...formData[sectionInputArray.UID],
                NestedListIDSingle(sectionInputArray),
              ],
            };

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z] /g, "")
              .substr(0, 11);

            let withRandom = {
              ...addedFormData,
              rand_value: randomVal,
            };

            // console.log({ addedFormData: addedFormData });

            setFormData(withRandom);
          }}
        >
          Add New {sectionInputArray.name}
        </button>

        {/* Button to remove section (or created form) */}
        <button
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick={() => {
            console.log(
              `${sectionInputArray.name}-${idx} section will be removed`
            );
            // formData[sectionInputArray.UID].splice(idx, 1);

            let formDataTarget = formData[sectionInputArray.UID];
            // console.log(formDataTarget);

            let newFD = formData;

            newFD[sectionInputArray.UID].splice(idx, 1);

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z] /g, "")
              .substr(0, 11);

            let withRandom = {
              ...newFD,
              rand_value: randomVal,
            };

            setFormData(withRandom);
          }}
        >
          Remove {sectionInputArray.name}
        </button>
        </>
        )}
      </section>
      </>
      
      );
    

CodePudding user response:

An example how to use the && in an expression to decide whether an element is rendered.

function Example() {
  const [showButton, setShowButton] = React.useState(true);
  
  return (
  <div className='example'>
    <div>some text</div>
    {
        showButton && <button onClick={() => setShowButton(!showButton)}>click me</button>
    }
  </div>)
}

Fiddler example

  • Related