Home > Enterprise >  React component creating extra div
React component creating extra div

Time:06-08

I'm working on converting some page elements into React components and I'm encountering a strange and difficult issue. I create the components normally like so:

const ComponentName = () => {
  return (
    <div className='styling-classes'>
      <SubComponentName />
    </div>
  )
}

and the component renders, but the problem is that React is wrapping it in an extra div that is breaking styling like so:

<div id='div-containing-component'>
  <!-- React sticks this in here -->
  <div id="ComponentName-react-component-a0838426-9f52-48be-99fd-d36745dceb35">
    <div className='styling-classes'>
      <!-- more component markup -->
    </div>
  </div>
</div>

Now I'm sure that there are good reasons for the library doing this, but rest assured, this is something that I DO NOT WANT. I don't care what the React teams reason is for this extra div, I'm working on a legacy app with enough CSS to fill an encyclopedia and this additional div is breaking styling in a way that simply isn't fixable. If I'm not able to eliminate it on my own I'll write a separate script to delete the extra div manually and relocate the enclosed markup but I'd prefer to not have to do all of that. Can anyone tell me how to get rid of this div that I didn't ask for and need to go away?

Edit: After looking more deeply it appears that this is something having to do with the "React on Rails" gem that I'm using (this is an RoR project) but I don't see the reason for or how to get rid of it.

CodePudding user response:

Ok, so I've managed to figure out what is going on and come up with a work around. Something I didn't know about the React on Rails library is that whenever a component is instantiated (something done in the view using a call to a #react_component method,) the gem creates what it calls a "wrapper" div which the actual component markup gets dropped into.

The solution is to remove the <div className='styling-classes'> from the component, and instead add the styling classes directly to the method call as an argument like so:

react_component('ComponentName', props: { key: val }, html_options: {class: 'styling-classes'})

It's not a perfect solution, and it breaks some of the encapsulation I'm going for with components but it works. Hope that this can help someone else some day. Thanks to all who lent their time and attention.

CodePudding user response:

This is specific to your rails application, can't help without more context.

  • Related