Ask A Question

Notifications

You’re not receiving notifications from this thread.

Best practices for structuring reusable frontend components (coming from Angular/React) ?

Cengiz Gürtusgil asked in Rails

Hey I'm an Angular developer diving into the Ruby on Rails, and I'm trying to figure out the best way to structure reusable frontend components, like buttons, in a Rails project. Especially because I use tailwind.
I'm used to creating component-based architectures in Angular/React,

My current approach
I came up with this pattern using partials:

<%# app/views/shared/_button.html.erb %>

<%
  base_classes = "rounded bg-gray-400 font-semibold text-white ..."

  size_classes = {
    xs: 'px-2 py-1 text-xs rounded',
    sm: 'px-2 py-1 text-sm rounded',
    md: 'px-2.5 py-1.5 text-sm rounded-md',
  }

  size ||= 'md'
  type ||= 'button'
  css_classes ||= ''

  button_classes = "#{base_classes} #{size_classes[size.to_sym]} #{css_classes}"
%>

<button type="<%= type %>" class="<%= button_classes.strip %>">
  <%= yield %>
</button>
However, using this component feels a bit cumbersome:
<%= render 'components/button' do %>
  Submit
<% end %>

Questions

  • Is there a better/more idiomatic way to structure reusable components in Rails? I saw the ViewComponents Libary, but it seems like a Overkill? I am a single developer who wants to ship Products in his free time after work. I am really interested in the 'one person framework' way of doing things
  • How do experienced Rails developers typically handle this kind of frontend reusability?
  • Is this component-based thinking even applicable in the Rails world, or am I approaching this from the wrong angle?

I'd really appreciate any insights, best practices, or resources you could share. Thanks in advance!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.