ViewComponent/view_component · error · ViewComponent::TranslateCalledBeforeRenderError

`#translate` can't be used before rendering as it depends on

Error message

`#translate` can't be used before rendering as it depends on the view context that only exists once a ViewComponent is passed to the Rails render pipeline.

It's sometimes possible to fix this issue by moving code dependent on `#translate` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void).

What it means

Error "`#translate` can't be used before rendering as it depends on the view context that only exists once a ViewComponent is passed to the Rails render pipeline. It's sometimes possible to fix this issue by moving code dependent on `#translate` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void)." thrown in ViewComponent/view_component.

Source

Thrown at lib/view_component/translatable.rb:94

      # Ensure the Simple backend won't load paths from ::I18n.load_path
      def load_translations
        super(@__vc_load_paths)
      end

      def scope_data(data)
        @__vc_i18n_scope.reverse_each do |part|
          data = {part => data}
        end
        data
      end

      def store_translations(locale, data, options = EMPTY_HASH)
        super(locale, scope_data(data), options)
      end
    end

    def translate(key = nil, **options)
      raise ViewComponent::TranslateCalledBeforeRenderError if view_context.nil?

      return @view_context.translate(key, **options) unless __vc_i18n_backend
      return key.map { |k| translate(k, **options) } if key.is_a?(Array)

      locale = options.delete(:locale) || ::I18n.locale
      key = self.class.__vc_i18n_key(key, options.delete(:scope))
      as_html = HTML_SAFE_TRANSLATION_KEY.match?(key)

      __vc_html_escape_translation_options!(options) if as_html

      if key.start_with?(__vc_i18n_scope + ".")
        translated =
          catch(:exception) do
            __vc_i18n_backend.translate(locale, key, options)
          end

        # Fallback to the global translations
        if translated.is_a? ::I18n::MissingTranslation

View on GitHub (pinned to 9f22c36fa7)

Solutions

  1. Move code that calls `#translate`/`#t` into a `#before_render` method or the template, where the view context exists.
  2. If a translation is needed at initialization time, call `I18n.t` directly with an explicit scope instead of the component's `#translate` helper.

When it happens

Trigger: Thrown at lib/view_component/translatable.rb:94 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of ViewComponent/view_component@9f22c36fa7 (2026-08-23). Data as JSON: /api/errors/2433ab1098fa6bd7. Report an issue: GitHub.