I'm trying to build a simple unit convertor to practice React.js. I want to be able to change the value of one unit eg: Kg, and have the other unit eg: lb to automatically change on the screen. Please see this website to give you an idea: http://www.convertunits.com/from/lb/to/kg
I have the following code, it renders but the units don't update. What I want to know is:
- Is it even accurate for one component to have
two states
? 1 forKg
and another forlb
- Or would they need to be
sibling components
? If so, how would they go about updating each other'sstates
? - If it's possible to have the state for both units in the same component, what am I doing wrong here?
Thank you! (I have a simple express app to render the page)
import React from 'react';
export default class Converter extends React.Component {
render() {
return (
<div className="convert">
<Range />
</div>
);
}
}
class Range extends React.Component {
constructor(props) {
super(props);
this.state = { kg: null, lb: null };
}
kgClick() {
this.setState({ lb: state.kg * 2.2046 });
}
lbClick() {
this.setState({ kg: state.lb / 2.2046 });
}
render() {
return (
<div>
<label> Kg: </label>
<input type="number" name="Kg" onChange={this.kgClick} value={this.state.kg} />
<label> Lb: </label>
<input type="number" name="Lb" onChange={this.lbClick} value={this.state.lb} />
</div>
);
}
}
Backend logic:
var express = require('express');
var app = express();
app.set('port', (9000));
app.set('view engine', 'jsx');
app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine({ transformViews: false }));
require('babel/register')({
ignore: false
});
app.use('/', function(req, res) {
res.render('index', "");
});
app.listen(app.get('port'), function() {});