user5096599
user5096599

Reputation:

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{

    constructor(){
        super();
    }

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

    render(){

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

Upvotes: 0

Views: 492

Answers (1)

zerkms
zerkms

Reputation: 254896

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.

Upvotes: 0

Related Questions