claudiopb
claudiopb

Reputation: 1090

ReactJS - Undefined Element

I have this component below and there is an error caused by the changeColor() function which results an error message:

TypeError: Cannot set property 'color' of undefined

It is the only error in the component. All the other things are working successfully. The JSON data is fetched good and the component renderization is fine too. Of course it was before I have implemented the function changeColor() which blocked the app.

import React, { Component } from 'react'

var data = require('./db.json');

class Cronology extends Component {
    constructor(props) {
        super(props)
        this.state = {
            cronology: [],
            year: "",
            description: ""
        }

        this.changeColor = this.changeColor.bind(this)
    }

    componentDidUpdate() {
        this.setState({
            cronology: data.cronology
        })

        this.changeColor();
    }

    changeColor() {
        document.querySelectorAll('p').style.color = 'red'
    }

    render() {
        return (
            <table>
                {
                    this.state.cronology && this.state.cronology.map(
                        (i) => {
                            return (
                                <tr>
                                    <th className="column1">• {i.year}</th>
                                    <th className="column2"><p>{i.description}</p></th>
                                </tr>
                            )
                        }
                    )
                }
            </table>
        )
    }
}
export default Cronology;

Upvotes: 2

Views: 575

Answers (2)

Matin Sasan
Matin Sasan

Reputation: 1885

As a supplement for others' answers, you can use forEach, that is:
document.querySelectorAll('p').forEach(el => el.style.color = 'red');

Upvotes: 1

JohnSnow
JohnSnow

Reputation: 454

Your changeColor() method is using document.querySelectorAll('p') which returns a collection. You have to target the specific element.

document.querySelectorAll('p')[0].style.color = "red" for example

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Upvotes: 4

Related Questions