Home > other >  Simplify repeating attributes across elements
Simplify repeating attributes across elements

Time:09-01

I'm new to React with react-bootstrap and what I'd like to achieve seems trivial, but didn't found the answer. Either I didn't have the correct search query or, it's simply not possible. I have multiple elements which share the same attributes

<Form>
  <Form.Control size="sm" plaintext={!editable} readOnly={!editable} value={title} />
  <Form.Control size="sm" plaintext={!editable} readOnly={!editable} value={desc} />
  <Form.Control size="sm" plaintext={!editable} readOnly={!editable} value={qtty} />
  <Form.Control size="sm" plaintext={!editable} readOnly={!editable} value={year} />
</Form>

Question: Is it possible to simplify with something like

const conf= `size="sm" plaintext=$(!editable) readOnly=$(editable)` // whatever the formatting

<Form>
  <Form.Control {conf} value={title} />
  <Form.Control {conf} value={desc} />
  <Form.Control {conf} value={qtty} />
  <Form.Control {conf} value={year} />
</Form>

Thanks for your Help

CodePudding user response:

This is what React is built for! You can easily make a FormControl component and simply pass in the different variables via props. It may look like this:


export default function FormControl(props) {

      const conf = {size: 'sm', plaintext: !editable, readonly: editable}

      return(
        <Form.Control {...conf} value= 
        {props.value} />
      )
}

Import the new FormControl component into your parent form page and it will end up looking like this:

<Form>
  <FormControl value={title} />
  <FormControl value={desc} />
  <FormControl value={qtty} />
  <FormControl value={year} />
</Form>

And if you want to really make it look decent, simply store all your values in an array and map over them into your new FormControl component:

<Form>
   {values.map(value => {
     <FormControl value={value} />
   })}
</Form>

If you need to change the style like size or plaintext, you can easily associate changes from the parent down to the FormControl component via props (just like we did with value).

CodePudding user response:

Response given by @yevhen Horbunkov is PERFECT ! Thanks.

If someone could mark the question as solved...

  • Related