Reputation: 95
I am getting error when I try to use this.username.value
. I want to get value of textbox to show in label. I am newbie to react. How to get value from Textbox to a variable and display in Label using InputRef.
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import TextBox from 'components/Atoms/TextBox';
import makeSelectTestPage from './selectors';
export class TestPage extends React.PureComponent {
constructor(props) {
super(props);
this.username ='',
this.handelChange = this.handelChange.bind(this);
}
handelChange() {
console.log("Log",this.username.value);
<label> this.username.value</label>
}
render() {
return (
<div>
<Helmet
title="TestPage"
meta={[
{ name: 'description', content: 'Description of TestPage' },
]}
/>
<TextBox labelName="Input Vaue" placeholder="Test" ref={(inputRef) => { this.username = inputRef; }} defaultValue="Text" ></TextBox>
<button onClick={this.handelChange}>Login</button>
</div>
);
}
}
TestPage.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
TestPage: makeSelectTestPage(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TestPage);
Upvotes: 0
Views: 7042
Reputation: 12084
In your question there are a few mistakes. Try to understand the next code and your will be able to apply it to your example :
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
value: "",
username: ""
}
}
handleChange(e){
this.setState({value: e.target.value})
}
handleClick(){
this.setState({username: this.state.value})
}
render(){
return (
<div>
<label>{this.state.username}</label><br />
<input value={this.state.value} onChange={this.handleChange.bind(this)}></input><br />
<button onClick={this.handleClick.bind(this)}>Login</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'/>
Upvotes: 1