React JSX integration with erb and Ruby block synt

2019-04-12 13:54发布

问题:

In my app/assets/javascripts/components/navbar.js.jsx.erb I can write something like this in the render function of my component (I'm using the gem react-rails):

class Navbar extends React.Component {
  render() {
    return(
      <div className="navbar-header">
        <ul>
          <li>
            <%= link_to root_path, className: 'navbar-brand' do %>
              <span className='glyphicon glyphicon-home'></span>
              &nbsp;
              <%= I18n.t('menu.now') %>
            <% end %>
          </li>
          <li><%= link_to I18n.t('menu.archive'), archive_path%></li>
        </ul>
      </div>
    );
  }
}

All works fine except for the link_to with block, which gives me a syntax error:

syntax error, unexpected keyword_end, expecting ')'

If I remove the block all works fine. Any idea?

PS: To use the Rails helpers, I have added these lines in config/initializers/assets.rb:

# Include Rails helpers in the assets pipeline
Rails.application.config.assets.configure do |env|
  env.context_class.class_eval do
    include ActionView::Helpers
    include Rails.application.routes.url_helpers
  end
end

回答1:

I think you need parenthesis around the parameters when u have a block following



回答2:

On the github react-rails page someone have answer at this question, see this comment: https://github.com/reactjs/react-rails/issues/211#issuecomment-178119941