I am trying to create a simple block converter for practicing React.js. I want to be able to change the value of one device, for example: Kg, and have another block, for example: lb, for automatic changes on the screen. Please check out this site to give you an idea: http://www.convertunits.com/from/lb/to/kg
I have the following code, it displays, but the blocks are not updated. I want to know:
- Is it possible for one component to have
two states ? 1 for Kg and another for lb - Or do they need to be
sibling components ? If so, how will they update each other's states ? - If it is possible to have state for both units in the same component, what am I doing wrong here?
Thanks! (I have a simple express application to display 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() {});
Anita source share