Search code examples
reactjsspringspring-bootthymeleaf

Use Thymeleaf variable in React


Is there a way to use a Thymeleaf variable in React?

I've read here that this is supposed to be a bad idea. The problem is, that I created a Spring Boot application with Thymeleaf, that incorporates a login mechanism. I got the Spring Boot Thymeleaf example from the security part (Part 5 - Securing the UI and the API) here.

I use Basic for authenticating with username/password. At the top of the <body> element a "Hello, Username" <div> displays the logged in user and a logout-button.

What I need is the username value, i.e. "greg". It is located in the Thymeleaf variable ${#authentication.name}. I would like to get that value and make use of it inside the React application bundled in built/bundle.js.

Is there any way to get the variable into React, i.e. set a globally accessible variable?

This is the index.html:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/main.css" />
</head>
<body>
    <div>
        Hello, <span id="managername" th:text="${#authentication.name}">user</span>.
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Log Out"/>
        </form>
    </div>
    <div th:with="message=${#authentication.name}"></div>

    <div id="app"></div>

    <script src="built/bundle.js"></script>
</body>
</html>

Solution

    1. In your index.html:

      <input type="hidden" id="th-username" th:value="${#authentication.name}"/>
      
    2. In your App.js:

      import $ from 'jquery';
      
      function App(){
        var username = $("#th-username").val();
      
      return (<div>{username}</div> )
      
      }