1

I have this form component that I created but in some cases I want it to have a button and in other cases I want it to have a text field instead of the input field like I have coded.

function FormTypeOne(props) {
  return (
    <form className={classes.form}>
      <div className={classes.control}>
        <label htmlFor={"title"}>{props.title}</label>
        <input type={props.type} required id={props.id} />
      </div>
    </form>
  )
}

Is it possible to add a button and a text field but then decide which one I want to use? Or do I need to make 3 different components?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Mooch
  • 113
  • 1
  • 8
  • It's really up to you and your use case please explain "but in some cases", so we could maybe recommend an approach for your use case – Pablo Recalde Feb 17 '22 at 23:59

2 Answers2

2

Yes you can provide your conditions in props, then display the right button depending on the props received :

function FormTypeOne({case1, case2}) {
  return (
    <form className={classes.form}>
      <div className={classes.control}>
        <label htmlFor={"title"}>{props.title}</label>
        <input type={props.type} required id={props.id} />
        {case1 && <button />}
        {case2 && <label />}
      </div>
    </form>
  )
}

So if case1 = true, it will display the button and if case2 is true, it will display the label

For example :

function NewMeetupForm() {
  return (
    <Card>
      {' '}
      <FormTypeOne title="Meetup Title" />
      <FormTypeOne title="Meetup Image" htmlFor="image" type="url" id="image" case1 />
      <FormTypeOne title="Address" type="text" id="address" case2 />
    </Card>
  );
}

So you will have button on the second one and label on the third one

Aznhar
  • 610
  • 1
  • 10
  • 30
1

You can send a prop to decide what to show

function FormTypeOne(props) {
  const htmlElem = useMemo(() => props.isButton ?
              <button /> : 
              <input type={props.type} required id={props.id} />
, [props.isButton])

  return (
    <form className={classes.form}>
      <div className={classes.control}>
      <label htmlFor={"title"}>{props.title}</label>
      {htmlElem}
      </div>
    </form>
  )
}

in this example use a boolean prop isButton

Hagai Harari
  • 2,767
  • 3
  • 11
  • 23
  • Using this example, how would I then call it in the following code? `function NewMeetupForm() { return ( ) } ` – Mooch Feb 18 '22 at 00:06