Wasteland Wasteland - 2 months ago 9
Javascript Question

ReactJS - pass values to a component

I've got a component where user inputs a number:



import React, { Component } from 'react';
import Place_holder from './place_holder';

class Body extends Component {
constructor(props) {
super(props);
this.state = { value: ""};
}

handleChange(value) {
this.setState({value});
}

render() {
return (
<div>
<input
type="number"
value={this.state.value}
onChange={event => this.handleChange(event.target.value)}
/>

<Place_holder num={this.state.value} />
</div>
)
}
}

export default Body;





The value gets passed to Place_holder where three different elements are supposed to do 3 different things (for the argument's sake: Column 1: num x 2, Column 2: num / 2, Column 3: num X num). Now as I type the number in the input box, it gets automatically updated in the three columns but whenever I try to write any method to apply to the number and change it in real time, I get all sorts of errors

import React, { Component } from 'react';


class Place_holder extends Component {
constructor(props) {
super(props);
}



render() {
return (
<div>
<div className="row">
<div className="col-md-4">{this.props.num}</div>
<div className="col-md-4">{this.props.num}</div>
<div className="col-md-4">{this.props.num}</div>
</div>
</div>
)
}
}

export default Place_holder;


How do I do it?

leo leo
Answer

Never modify props directly, instead compute what you need from them.

For example:

render() {
    const column1 = this.props.num*2;
    const column2 = this.props.num/2;
    const column3 = this.props.num*this.props.num;

    return (
        <div>
            <div className="row">
                <div className="col-md-4">{column1}</div>
                <div className="col-md-4">{column2}</div>
                <div className="col-md-4">{column3}</div>
            </div>
        </div>
    )
}