Rails Form Labels built with ViewComponent and Tailwind CSS
Rails Designer’s FormLabelComponent is as simple as it’s elegant. Simply pass the Form Builder object and the field, and upon a validation error the label will show the validation error and changes text color. This code preview may have been simplified for demonstration purposes. When you generate this component using Rails Designer it uses your settings.
class FormLabelComponent < ViewComponent::Base
def initialize(form:, field:, label: nil)
@form = form
@field = field
@label = label
end
erb_template <<-ERB
<%= @form.label @field, label_value, class: css %>
ERB
private
def label_value
return field_error_message if has_errors?
@label.presence || default_label_value
end
def css
class_names(
"text-sm text-gray-700 font-medium",
{
"text-red-600": has_errors?
}
)
end
def field_error_message = @form.object.errors.full_messages_for(@field).first
def default_label_value = I18n.t("labels.#{@field}", default: @field.to_s.capitalize)
def has_errors? = @form.object.errors.full_messages_for(@field).any?
end
UI components Library for Ruby on Rails apps
$
99
one-time
payment
View components