yuusuke-roughの日記

Java,SpringBoot,趣味等

htmlにある値を静的アセットから読みこむ in SpringBoot + React + Typescript

目的

SpringBootで用意したhtmlにある要素の値を取り出す。

 

前提

tsxを使用しています。

 

内容

 

下記にある「隠しているよ」の値を取り出す。

<input id="test" type="hidden" value="隠しているよ">
  <div id="root"></div>
  <script type="module" th:src="@{/dist/assets/main-Dd_RwVU1.js}"></script>

 

React側では下記のように型を指定して値を取りだしている。

function App() {
  const [count, setCount] = useState(0)
  const text: string = (document.getElementById("test")as HTMLInputElement)?.value ?? "";
  return (
    <>
<div style={{ position: "relative", height: "500px" }}>
        <MainContainer>
          <ChatContainer>
            <MessageList>
              <Message
                model={{
                  message: text,
                  sentTime: "just now",
                  sender: "Joe",
                  position: "normal",
                  direction: "incoming"
                }}
              />
            </MessageList>
            <MessageInput placeholder="Type message here" />
          </ChatContainer>
        </MainContainer>
      </div>;
    </>
 略…

 

 

input要素はHTMLInputElementであるから、valueインスタンスプロパティとして定義されており、入力要素の型のみに適用される。

一方で、Div要素はHTMLDivElementであるから、Nodeのインスタンスプロパティで定義されているtextContentを使用して値の取得もできる。

 

要素が存在しない場合にnullが返ってくるようにdocument.getElementByIdの後に「?」をつけている。

また、値がnullやundefinedの場合にデフォルトの値が返ってくるように「??」としている。