unhurried

コンピュータ関連ネタがほとんど、ときどき趣味も…

React Quick Startを簡単に復習できるサンプルコード

Webアプリのアイデアがふと思い浮かんだので、開発するときにこれまで使ったことのないライブラリを導入してみようと、Reactに挑戦しています。
Reactはドキュメントが充実していて大変素晴らしいのですが、私は物覚えが悪いので一度読んでもすぐに忘れてしまうことが多いです。ですのでいつも後でさっと見返せるように自分用に簡単なメモを作るのですが、このメモがもしかするとどなたかの役に立つかもしれないと思いましたので、ご紹介します。

今回はReact Quick Startをポイントをまとめたサンプルコードです。
(CodePenにも登録しています:React Cheat Sheet

// React Element

// Tag syntax like "<p> ... </p>" is called JSX, and JSX produces a React element.
// React elements are the descriptions of what you want to see on the screen.
// React elements are imuutable and they can't be changed once they are defined.
// (See following React components for how you can update the DOM.)
const singleLineElement = <p>Hello World.</p>;

// When you split JSX over multiple lines, 
// it is recommended to wrap it in parentheses to avoid automatic semicolon insertion by editors.
// Expressions can be embedded in JSX. (JSX itself is also an expression.)
// React escapes any values embedded in JSX before rendering them to prevent injection attacks.
const href = "https://www.time.gov/";
const multipleLinesElement = (
    <p>
        <a href={href} >Current Time: {new Date().toLocaleTimeString()}</a>
    </p>
);

// React Component
// React components accept inputs (props) and return React elements.
// They can be defined with "function" or "class", and used in JSX format like "<MyComponents />".

// React component in the "class" style
// React component extends React.Component class.
// Component name (= class name) must be started with a capital letter.
class ClassComponent extends React.Component {

    // Constructor recieves JSX attributes as a single props object.
    // React component must not modify its own props.  
    constructor(props) {

        // Constructor should always call the base constructor with props.
        super(props);

        // this.state is a special object used to store the state of the component.
        // this.state can be initialized only in the constructor.
        this.state = {value: 1};

        // Assign "this" to methods to handle events.
        this.handleChange = this.handleChange.bind(this);
    }

    // Define a method to handle an event.
    // React passes SyntheticEvent according to the W3C spec.
    handleChange(event) {

    // Use setState() method to modify the state.
    // setState() merges the object you provide into the current state.
    this.setState({value: event.target.value});
    // Use callback when you modify the state based on previous state.
    // (The update of the state may be asynchronous.)
    //     this.setState((prevState, props) => ({
    //         counter: prevState.counter + props.increment
    //     }));
    }
    
    // render() returns a single root React element which will be shown in the DOM. 
    // If render() returns null, the component will not be rendered.
    render() {
        return (
            <div>
                <form>
                    <input type="number" value={this.state.value} onChange={this.handleChange} />
                </form>
                <FunctionComponent number={this.state.value} />
            </div>
        );
    }

    // componentDidMount() is called after the component output has been rendered to the DOM.
    componentDidMount() {
        console.log("componentDidMount()");
    }

    // componentWillUnmount() is called when the component is being removed from the DOM.
    componentWillUnmount() {
        console.log("componentWillMount()");
    }
}

// React component in the "function" style
function FunctionComponent(props) {

    const number = props.number;
  console.log(number);
    var listItems = [];
    // When you define a list, a "key" attribute needs to be specifined in every element of the list.
    // (Keys help React identify which items have changed, are added, or are removed.)
    // Keys used within arrays should be unique among their siblings.
    for(var i=0; i<number; i++) {
// for(var i=0; i<number; i++) {
        listItems.push(
            <li key={i.toString()}>{i+1}</li>
        );
    }

    return (
        <ul>{listItems}</ul>
    );
}

// ReactDOM.render() renders React components (or elements).
// Pass a component or an elemment to render and root DOM where you want to show it.
// React DOM updates only necessary parts of the DOM.
ReactDOM.render(
    <ClassComponent />,
    document.getElementById('root')
);