Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to manipulate the DOM in a React component

Tags:

dom

reactjs

I can't manipulate the <div id="chart"> either in componentWillMount or componentDidMount lifecycle methods.

document.getElementById("chart") returns null in both the methods. Should I not use the raw DOM manipulation function or should I use something else to achieve the same which is manipulate the <div id="chart">

import React from 'react'

export default class D3Chart extends React.Component {
    constructor () {
        super();
    }

    componentWillMount() {
         document.getElementById("chart").innerText = "Testing";
    }

    componentDidMount () {
        document.getElementById("chart").innerText = "Testing";
    }

    render() {
            return (<div id="chart"></div>
        )
    };
}
like image 399
wonderful world Avatar asked Aug 23 '15 21:08

wonderful world


1 Answers

Just use ref like the React guys recommend:

import React from 'react';
import ReactDOM from 'react-dom';

export default class D3Chart extends React.Component {
    constructor () {
        super();
    }

    componentDidMount () {
        this.refs.chart.innerText = "Testing";
    }

    render() {
        return <div id="chart" ref="chart"></div>;
    }
}

And here's the Fiddle.

like image 51
lyosef Avatar answered Oct 06 '22 01:10

lyosef