Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX and Django reverse URL

I'm trying to build some menu using React and need some Django reverse urls in this menu. Is it possible to get django url tag inside JSX? How can this be used?

render: function() {
    return <div>
        <ul className={"myClassName"}>

            <li><a href="{% url 'my_revese_url' %}">Menu item</a></li>

        </ul>
    </div>;
} 
like image 956
Goran Avatar asked Aug 31 '25 22:08

Goran


1 Answers

You could create a script tag in your page to inject the values from Django into an array.

<script>
  var menuItems = [
    {title: 'Menu Item', url: '{% url "my_reverse_url" %}'},
    {title: 'Another Item', url: '{% url "another_reverse_url" %}'},
  ];
</script>

You could then pass the array into the menu through a property.

<MyMenu items={menuItems}></MyMenu>

Then loop over it to create the list items in your render method.

render: function(){ 
  var createItem = function(itemText) {
    return <li>{itemText}</li>;
  };
  return <ul>{this.props.items.map(createItem)}</ul>;
}

This will keep your component decoupled and reusable because the logic for creating the data and the logic for displaying the list items is kept separate.

like image 175
Soviut Avatar answered Sep 03 '25 14:09

Soviut