React.js プロパティ値を渡す

React.js プロパティ値を渡す

React.jsで、プロパティ値を渡す手順を記述してます。

環境

  • OS  windows 11 home
  • node v16.13.2
  • npm 8.1.2
  • yarn 1.22.17
  • React 17.0.2
  • ブラウザ Edge 99.0.1150.39

react.js環境構築

下記のコマンドで構築してます。ここでは、「react-test」という名前でプロジェクトを作成してます。

> yarn global add create-react-app
> npx create-react-app react-test

※「yarn」は以下のコマンドでインストール可能です。

> npm install -g yarn

作成したプロジェクトに移動しておきます。

> cd react-app

フォルダ構成

プロパティ値を渡す

「props」を使用すれば、コンポーネントにプロパティ値を渡すことが可能です。

「index.js」を以下のように編集してプロパティ「msg」を作成します。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App msg="Hello World"/>
  </React.StrictMode>,  
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

「App.js」で「props」を使用して、値を受け取ります。

import logo from "./logo.svg";
import "./App.css";

function App(props) {

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />        
        <p>{props.msg}</p>
      </header>
    </div>
  );
}

export default App;

実行します。

> yarn start

ブラウザから http://プライベートIP:3000にアクセスすると、プロパティ値が表示されていることが確認できます。