JKhan
JKhan

Reputation: 1287

Reactjs. Cannot pass variable to class

I m totally new to React. I am trying to pass a variable 'name' to my class, but it is not getting assigned. These names comes from another file. I cannot see names of people on my buttons. Before my Card was just a simple function and it was working fine. But after converting it into a class, name is not working. Pls help!

BEFORE (Working):

const Card = ({name, email}) => {

return  (

        <div>
            <h2 className='f5'>{name}</h2>
            <p className='f6'>{email}</p>
        </div>

    </div>
);
}

AFTER (Not Working):

class Card extends Component { 
    constructor({props, name}) {
        super(props);
        this.state = { 
            isToggleOn: true,
            name: this.name
        };

        this.handleClick = this.handleClick.bind(this);
 }

handleClick() {
    this.setState(prevState => ({
        isToggleOn: !prevState.isToggleOn
    }));
} 
render() {
    var { name } = this.state;
    return (
        <button onClick={this.handleClick}>
            { this.state.isToggleOn ? name : 'OFF' }
        </button>
    );  
    }
} 

ReactDOM.render(
  <Card />,
  document.getElementById('root')
);
export default Card;

Upvotes: 0

Views: 72

Answers (2)

Bogdan M.
Bogdan M.

Reputation: 2181

The variable name should be passed by the special parameter props. All varaibles coming from outside the compnent are passed via props.

ReactDOM.render(
  <Card name="Some name"/>,
  document.getElementById('root')
);

Then in the constructor:

constructor(props) { // NOTE that only props gets passed to to constructor
     super(props)
     this.state = { 
        isToggleOn: true,
        name: props.name
};

This way you can set the state values in constructor, having the variable from outside.

I recommend you strongly to check out the official tutorial: https://reactjs.org/docs/introducing-jsx.html

Upvotes: 0

CristianCurteanu
CristianCurteanu

Reputation: 46

First, I think you should change this piece of code:

this.state = { 
    isToggleOn: true,
    name: this.name
};

to this:

this.state = {
    isToggleOn: true,
    name:       name || ''
};

as you want to use the value of parameter.

Second, I don't think this is a root component, so most probably you should use it inside other component, which means that this piece of code:

ReactDOM.render(
  <Card />,
  document.getElementById('root')
);

is redundant, so you will need to remove it from current file.

And last, when you will use the Card component in another component, you should give it name property, something like:

<Card name="Some String" />

Upvotes: 1

Related Questions