Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Props is not defined React js

I'm using react js and I don't know why I'm getting props isn't defined.

Here is my class.

import React, { Component } from 'react';

const InputHeight = {
    height: '50px',
}

function clearData() {
    this.refs.input.value = "";
}



export default class TextInput extends Component {
    render() {
        return (
            <input
                className="form-control"
                ref="input"
                name={props.name}
                type={props.inputType}
                value={props.content}
                pattern={props.pattern}
                onChange={props.controlFunc}
                placeholder={props.placeholder}
                style={InputHeight}
                required />
        );
    }
}


TextInput.propTypes = {
    inputType: React.PropTypes.oneOf(['text', 'number', 'email']).isRequired,
    name: React.PropTypes.string.isRequired,
    controlFunc: React.PropTypes.func.isRequired,
    content: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ]).isRequired,
    placeholder: React.PropTypes.string,
};

Failed to compile ./src/components/Parts/SmallBits/FormItems/TextInput.js Line 19: 'props' is not defined no-undef Line 20: 'props' is not defined no-undef Line 21: 'props' is not defined no-undef Line 22: 'props' is not defined no-undef Line 23: 'props' is not defined no-undef Line 24: 'props' is not defined no-undef

Search for the keywords to learn more about each error.

this.refs.form.clearData();

just onClick that and it gives me

Uncaught TypeError: Cannot read property 'refs' of null

like image 939
andy wilson Avatar asked Jun 30 '17 15:06

andy wilson


1 Answers

In a class the way to access props is this.props not just props.

export default class TextInput extends Component {
    render() {
        return (
            <input
                className="form-control"
                ref="input"
                name={this.props.name}
                type={this.props.inputType}
                value={this.props.content}
                pattern={this.props.pattern}
                onChange={this.props.controlFunc}
                placeholder={this.props.placeholder}
                style={InputHeight}
                required />
        );
    }
}

Here is your code revised with this change.

As for this function

function clearData() {
    this.refs.input.value = "";
}

You have 2 issues I believe. First, it is not nested within the class so the this keyword is not referring to this class. Second, even if it was nested, once the caller calls this function, the this keyword's context would now no longer be referring to your class. It is important to understand how the this keyword works and how to either use bind or => functions to get around this behavior.

like image 133
Chaim Friedman Avatar answered Oct 13 '22 23:10

Chaim Friedman