Search code examples
javascriptreactjsdomdocumentgetelementsbytagname

Access DOM in render() of React (v15)


While I study React, I found the following code.

As far as I understand, DOM in React is usually accessed via Refs.

However, this code uses document, and I haven't seen any one uses this way.

Do I misunderstand? Is this formal way?

Plus, document.form is same with document.getElementByTagName("form")?

Any reference would be helpful.

    export default class IssueAdd extends React.Component {
    constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        e.preventDefault();
        const form = document.forms.issueAdd;
        this.props.createIssue({
            owner: form.owner.value,
            title: form.title.value,
            status: 'New',
            created: new Date(),
        });
        form.owner.value = '';
        form.title.value = '';
    }

    render() {
        return (
            <div>
                <form name="issueAdd" onSubmit={this.handleSubmit}>
                    <input type="text" name="owner" placeholder="Owner" />
                    <input type="text" name="title" placeholder="Title" />
                    <button>Add</button>
                </form>
            </div>
        );
    }
}

Solution

  • React is just another javascript library, so it has all the powers that you might have used in a plain javascript like, access to window object or document object. But does that mean you should use them, absolutely NO and you will find the reasons here. Direct DOM manipulation is very costly operation.

    Basically, React works on the concept of virtual DOM. Virtual DOM makes it way too easy and faster for React to update the actual DOM, without going over the overhead of multiple direct DOM manipulations.

    Coming to refs, since we don't want to access a HTML element using document object React provided Refs, which will help to get into a specific element and access it quickly (it will return data from virtual DOM).

    Couple of good articles on refs:

    and off course

    BTW: Welcome to the wonderful world of React :)