Home > Back-end >  React: Is it possible to make things like buttons or text areas be part of the component code but th
React: Is it possible to make things like buttons or text areas be part of the component code but th

Time:02-18

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related