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);
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'/>
Here is the fiddle.
Related
So I have this parent which clone and injects props Login to the children:
import React, { Component } from 'react';
import { Container } from 'reactstrap';
import { NavMenu } from '../navigations/NavMenu';
import { Login } from './account/Login';
export class Layout extends Component {
static displayName = Layout.name;
render() {
const loginForm = new Login();
const childrenWithProps = React.Children.map(this.props.children, child => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { loginForm: loginForm });
}
return child;
});
return (
<div>
{loginForm.render()}
<NavMenu />
<Container>
{childrenWithProps}
</Container>
</div>
);
}
}
This is one of the children:
import React, { Component } from 'react';
import { http } from '../../helpers/Http';
export class FetchData extends Component {
static displayName = FetchData.name;
constructor(props) {
super(props);
this.state = { forecasts: [], loading: true };
let x = this.props.loginForm; <-- THIS IS UNDEFINED
}
.......
}
The this.props.loginForm is undefined. How can I inject props correctly?
EDIT
This is the Login component:
import React, { Component } from 'react';
import './Login.css';
export class Login extends Component {
constructor(props) {
super(props);
this.state = { show: false };
this.login = this.login.bind(this);
this.showLogin = this.showLogin.bind(this);
}
showLogin() {
this.setState({
show: true
});
}
login() {
}
render() {
return (
<form className={this.state.show ? "login-form " : "login-form hide"} onSubmit={this.login()}>
<h1>Login</h1>
<div className="form-group">
<input required type="text" placeholder="Email" />
<input required type="password" placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary">Login</button>
</form>
);
}
}
I want to call showLogin() from FetchData. If the user is not authorized when fetching the data, I want to show the login modal.
I want to make an app so that when text is typed in input element this will reflect that change in output. So far the updating doesn't work :(
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component {
state = {
user: [
{ username: 'Kai' },
{ username: 'Orange' }
]
}
inputChangeHandler = (e) => {
this.setState(
{
user: [
{ username: e.target.value },
{ username: e.target.value }
]
}
)
}
render() {
return (
<div className="App">
<UserInput onChange={this.inputChangeHandler} />
<UserOutput username={this.state.user[0].username} />
<UserOutput username={this.state.user[1].username} />
</div>
);
}
}
export default App;
Change in text typed in input element should be reflected as username rendered in UserOutput. This doesn't work.
Here are codes for other components...
import React, { Component } from 'react';
class UserInput extends Component
{
render() {
return(
<div>
<input />
</div>
);
}
}
export default UserInput;
and
import React, { Component } from 'react';
class UserOutput extends Component
{
render() {
return(
<div>
<p>First paragraph and my name is {this.props.username}</p>
<p>Second paragraph </p>
</div>
);
}
}
export default UserOutput;
Ok there's your problem. You're not assigning the change handler to the input element in your UserInput component. It should be:
<input onChange={this.props.onChange} />
I´m having troubles making the Input from the text area go to the Marked interpreter (getting a TypeError: Cannot read property 'value' of null). Any ideas on how to fix it?
Text area input:
import React, { Component } from 'react';
import './App.css';
import marked from "marked";
import MarkdownExample from "./previewer";
class Editor extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Some markdown text.'
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
createMarkup()
{
return {__html: marked(this.state.value)};
}
render() {
return (
<div>
<textarea value={this.state.value} onChange={this.handleChange}/>
<MarkdownExample />
</div>
);
}
}
Previewer:
import React, { Component } from 'react';
import './App.css';
import marked from "marked";
class MarkdownExample extends React.Component {
getMarkdownText(props) {
var rawMarkup = marked(this.state.value, {sanitize: true});
return { __html: rawMarkup };
}
render() {
return <div dangerouslySetInnerHTML={this.state.value.getMarkdownText()} />
}
}
export default MarkdownExample;
You cannot access state directly from parent, but you can pass the prop to the child
import React, { Component } from 'react';
import './App.css';
import marked from "marked";
import MarkdownExample from "./previewer";
class Editor extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Some markdown text.'
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
createMarkup()
{
return {__html: marked(this.state.value)};
}
render() {
return (
<div>
<textarea value={this.state.value} onChange={this.handleChange}/>
<MarkdownExample parentValue={this.state.value}/>
</div>
);
}
}
Previewers:
import React, { Component } from 'react';
import './App.css';
import marked from "marked";
class MarkdownExample extends React.Component {
getMarkdownText() {
var rawMarkup = marked(this.props.parentValue, {sanitize: true});
return { __html: rawMarkup };
}
render() {
return <div dangerouslySetInnerHTML={this.getMarkdownText()} />
}
}
export default MarkdownExample;
I am following this tutorial React Tutorial
Here is the thing:
I am calling function createTask from create-todo.js;
the function is defined in app.js
app.js
import React from 'react';
import ToDosList from './todos-list';
import CreateToDoItem from './create-todo-item'
const todoitems=[
{
task: 'finish react todo tutorial',
isCompleted: false
},
{
task: 'eat lunch',
isCompleted: true
}
];
export default class App extends React.Component
{
constructor(props){
super(props)
this.state={
todoitems
};
}
render()
{
return(
<div>
<h1>React Demo App - ToDos </h1>
<CreateToDoItem createtask ={this.createTask.bind(this)}/>
<ToDosList
todoitems={this.state.todoitems}
/>
</div>
);
}
createTask(task)
{
//alert('called');
this.state.todoitems.push({
task,
isCompleted:false
});
this.setState({todoitems: this.state.todoitems});
}
}
create-todo.js
import React from 'react';
import App from './app';
export default class CreateToDoItem extends React.Component
{
render()
{
return(
<form onSubmit={this.handleCreate.bind(this)}>
<input type="text" placeholder="what do I need to do?" ref="createInput"/>
<button>Create</button>
</form>
);
}
handleCreate(event)
{
event.preventDefault();
//alert('called');
this.props.createTask(this.refs.createInput.value); //this throws error
}
}
I am absolutely new to React.js. I don't know how this works. Should the function be available to create-todo.js? The code is exactly how it is shown in the tutorial.
Reason is, you are passing the function in props by a different key and using inside child by a different key.
Actual function name: createTask
Passing in props by key: createtask
Using inside child by: createTask
so use this.props.createtask() instead of this.props.createTask()
Your prop is named "createtask". You should probably change your prop name to createTask (as opposed to changing references to this.props.createtask).
You could do like this:
import React from 'react';
import ToDosList from './todos-list';
import CreateToDoItem from './create-todo-item'
const items = [
{
task: 'finish react todo tutorial',
isCompleted: false
},
{
task: 'eat lunch',
isCompleted: true
}
];
export default class App extends React.Component {
state = {
todoitems: items,
taskItem: ''
}
handleChange = (e) => {
this.setState({
taskItem: e.target.value
})
}
handleCreate = () => {
e.preventDefault()
item = {
task: taskItem,
isCompleted: false // default value
}
this.setState({
todoitems: [...this.state.todoitems, item ]
})
}
render() {
return (
<div>
<h1>React Demo App - ToDos </h1>
<CreateToDoItem
handleChange={this.handleChange}
handleCreate={this.handleCreate}
taskItem={this.state.taskItem}
/>
<ToDosList todoitems={this.state.todoitems}
/>
</div>
);
}
}
Then your form will be:
import React from 'react';
import App from './app';
export const CreateToDoItem = (props) => (
<form onSubmit={props.handleCreate}>
<input type="text" placeholder="what do I need to do?"
onChange={props.handleChange}
value={props.taskItem} />
<button type='submit'>Create</button>
</form>
);
I hope it help you :)
Kindly,
I would like to have, an Add button. The following is the React.js code that I thought is one way of implement the logic that I want, but unfortunately it's doesn't work.
my getting this Error:
bundle.js:47 Uncaught Error: Cannot find module "./src/index.js"
at webpackMissingModule at Object.<anonymous>
at __webpack_require__
How do I solve this problem?
import React from "react"
import ReactDOM from "react-dom"
import SearchBar from "./components/search_bar"
const API_KEY = "TheRealAPIKeyWouldGoHere"
const App = () => {
handleChange(value){
this.setState({
value: event.target.value
});
}
return ( <div>
<SearchBar onChange={this.handleChange}/>
</div>
)
}
ReactDOM.render(<App />, document.querySelector(".container"))
This is my component. I have assigned Button to input but i can't figure out how to make it work.
import React, { Component } from "react"
class SearchBar extends Component {
constructor(props){
super(props)
this.state = {term: ""}
}
handleChange(evt){
this.props.onChange(value);
}
render () {
return <div>
<button onClick={this.handleChange}>Search</button>
<input ref="inputName" onChange= { event => console.log(event.target.value)} />
</div>
}
}
export default SearchBar
In your component:
import React, { Component } from "react"
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = { term: '' }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.term })
}
handleSubmit(event) {
console.log(event.target.value)
event.preventDefault()
}
render() {
return (
<div>
<button onClick={this.handleSubmit}>Search</button>
<input
type="text"
value={this.state.term}
onClick={this.handleChange}
/>
</div>
)
}
}
export default SearchBar