Mike Mike -4 years ago 198
React JSX Question

My ID keeps returning null

I am learning ReactJS and attempting to console.log my id when the checkbox is checked. I have tried multiple ways to do this and I either get an error, undefined, or null. When it renders, the span tags do have their own id. How do I reference it from the function?

import React from "react";
import * as ToDoAction from "../actions/ToDoAction";

export default class ToDoLi extends React.Component{


let id = document.getElementById('id');
console.log('I am here at ' + id);


return (
<li onChange={this.deleteToDo.bind(this)}><input type="checkbox"/><span id={this.props.id} className="m-l-10">{this.props.text}</span></li>

Answer Source

Why you could not find the element: most likely its id attribute value was not set to the id literally. To confirm that you need to provide how you render this component.

But this practice is highly discouraged, one should not mess with DOM directly.

What you should have done instead:

  1. If you really need for some reason to get the dom element - learn how to use ref: https://facebook.github.io/react/docs/refs-and-the-dom.html

  2. Alternatively you may want to explore through the event that is passed to a handler. For that declare your handler as deleteToDo(e) and inspect e

  3. Otherwise - the this.props and all other react properties are available and you can use any of those.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download