How to accept and pass two parameter as props - reactjs

Hi I need to pass two parameters, to the class Chat. Currently it is getting only one parameter and displaying correctly.
const Chat = props => (
<div >
<ul>{props.messages.map(message => <li key={message}>{message}</li>)}</ul>
</div>
);
This Chat.js file is called from the Home.js. Suppose I need to pass the Chat component two parameters and I tried it like following.
import React, { Component } from 'react';
import { User } from './User';
import Chat from './Chat';
export class Home extends Component {
displayName = Home.name
state = {
messages: [],
names: []
};
handleSubmit = (message,name) =>
this.setState(currentState => ({
messages: [...currentState.messages, message],
names: [...currentState.names,name]
}));
render() {
return (
<div>
<div>
<User onSubmit={this.handleSubmit} />
</div>
<div>
<Chat messages={this.state.messages,this.state.name} />
</div>
</div>
);
}
}
In this scenario how should I change the Chat component to accept two parameters and display inside div tags.
This is what I tried. But seems it is incorrect.
const Chat = props => (
<div >
<ul>{props.messages.map((message, name) => <li key={message}>{message}</li> <li key={name}>{name}</li>)}</ul>
</div>
);
PS: The User Method
import * as React from 'react';
export class User extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
message: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div className="panel panel-default" id="frame1" onSubmit={this.handleSubmit}>
<form className="form-horizontal" action="/action_page.php" >
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="name">Your Name </label>
<div className="col-sm-10">
<input type="text" className="form-control" name="name" placeholder="Enter your Name" onChange={this.handleChange} />
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="message">Message</label>
<div className="col-sm-10">
<input type="text" className="form-control" name="message" placeholder="Enter your Message" onChange={this.handleChange}/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" id="submit" className="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
);
}
handleChange(evt) {
this.setState({ [evt.target.name]: evt.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
this.props.onSubmit(this.state.message, this.state.name);
this.setState({ message: "" });
this.setState({name:""});
};
}

You can do this by using separate attributes to pass different props. So for instance, you might revise your <Home/> components render method like so:
<Chat messages={this.state.messages} names={this.state.names} />
and then to access these two bits of data (messages and name) from inside the <Chat /> component you could do the following:
const Chat = props => (
<div >
<ul>{props.messages.map((message, index) => <li key={message}>
From: { Array.isArray(props.names) ? props.names[index] : '-' }
Message: {message}</li>)}
</ul>
</div>
);
Hope this helps!

You have to pass them separately:
<Chat messages={this.state.messages} name={this.state.name} />

Related

Render html based on the radio select

I have two radio buttons and need to render a different form for each when the user click the continue button, how can I do this? Here's the code I have so far.
class App extends Component {
constructor() {
super();
this.state = {
name: "typeOfInternet"
};
this.onChangeValue = this.onChangeValue.bind(this);
}
onChangeValue(event) {
console.log(event.target.value);
}
handleChange = () =>
this.setState({ showComponent: !this.state.showComponent });
render() {
return (
<Container>
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block" onChange={this.onChangeValue}>
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
/>
<label for="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
/>
<label for="empresarial">Internet Empresarial</label>
</div>
</div>
<div className="continue">
<button
className="btn-continue"
>
Continue
</button>
</div>
</section>
</Container>
)
}
}
export default App ;
The difference between codes are some input fields that "imternet Empresarial" has and "Internet Residencial" does not
There is no need for onChangeValue function because you're not calling it anywhere instead you can attach handleChange function to the <input> tags.
You should use the name which is provided in <input> inside state. So that it will be easier to use in setState.
There's no need to use .bind() also, with the help of arrow functions => you can escape that.
Inside switch, on different cases of the values instead of using <div>...</div>, you can call different components present in separate file. (in order to make the component readable)
Codesandbox Demo
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
internet: ""
};
}
handleChange = (e) => this.setState({ [e.target.name]: e.target.value });
renderForm = () => {
switch (this.state.internet) {
case "residencial":
return (
<div>
<h1>residencial form</h1>
</div>
);
case "empresarial":
return (
<div>
<h1>empresarial form</h1>
</div>
);
default:
return null;
}
};
render() {
return (
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block" onChange={this.onChangeValue}>
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
onChange={this.handleChange}
/>
<label htmlFor="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
onChange={this.handleChange}
/>
<label htmlFor="empresarial">Internet Empresarial</label>
</div>
</div>
{this.renderForm()}
<div className="continue">
<button className="btn-continue">Continue</button>
</div>
</section>
);
}
}
export default App;
First, you need to create your form element to render when radio buttons get toggled. Something like this:
const Form = ({ type }) => {
return type === "residencial" ? <div>Form 1</div> : <div>Form 2</div>;
};
Then keep track of the currently checked radio button and whether or not the continue button has been pressed. Something like this would work (Sandbox):
const Form = ({ type }) => {
return type === "residencial" ? <div>Form 1</div> : <div>Form 2</div>;
};
class App extends Component {
constructor() {
super();
this.state = {
name: "",
step: 1
};
}
onChangeValue = (event) => {
console.log(event.target.value);
this.setState({ name: event.target.value });
};
handleContinue = () => {
this.setState({ step: 2 });
};
render() {
const { step, name } = this.state;
return (
<div>
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block">
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
onChange={this.onChangeValue}
/>
<label for="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
onChange={this.onChangeValue}
/>
<label for="empresarial">Internet Empresarial</label>
</div>
</div>
<div className="continue">
<button
disabled={name === ""}
className="btn-continue"
onClick={this.handleContinue}
>
Continue
</button>
<hr />
{step === 2 ? <Form type={name} /> : null}
</div>
</section>
</div>
);
}
}
export default App;
There is also no need to bind your class functions, just use arrow functions, they will make your life much easier.

How to change form inputs in React and post using axios?

I'm learning React, but not strong yet. I use a component with form, that recieve data from express backend using axios.
There is no problems with get the correct data and render it in the form inputs, but i can't cope how to change input values and post using axios. I read something about handleChange() and other staff, but it's too hard yet.
The JSON looks like this:
{
"data": [
{
"_id": "5d28a6fcec97b111c2f5867d",
"phone": "+1 (111) 111 11 11",
"email": "shutruk#gmail.com",
"title": "khkjhkjhkj",
"longTitle": "lkjlkjlkjlk",
"introTitle": "Shutruk",
"introLongTitle": "Shutruk-Nahhunte",
"videoLink": "khkjhkjhkj",
"introText": "lkjlkjlkjlk",
"__v": 0
}
]
}
Here is the component:
import React, { Component } from 'react';
import axios from 'axios';
class Misc extends Component {
state = {
data: [],
loading: true,
error: false,
}
componentDidMount() {
axios.get('http://localhost:5555/data')
.then(res => {
const data = res.data.data; // get the data array instead of object
this.setState({ data, loading: false });
console.log(data);
})
.catch(err => { // log request error and prevent access to undefined state
this.setState({ loading: false, error: true });
console.error(err);
})
}
render() {
if (this.state.loading) {
return(
<div>
<p> Loading... </p>
</div>
)
}
if (this.state.error || !this.state.data[0]) { // if request failed or data is empty don't try to access it either
return(
<div>
<p> An error occured </p>
</div>
)
}
return (
<form action="">
<h2 className="center" >Change data</h2>
<div className="center"><img src={require('../img/orn.png')} alt="" className="orn"/></div>
<h5>Phone:</h5>
<input type="text" value={ this.state.data[0].phone } />
<h5>Email:</h5>
<input type="text" value={ this.state.data[0].email } />
<h5>Title:</h5>
<input type="text" value={ this.state.data[0].title }/>
<h5>Longtitle:</h5>
<input type="text" value={ this.state.data[0].longTitle }/>
<h2 className="center" >Intro:</h2>
<div className="center"><img src={require('../img/orn.png')} alt="" className="orn"/></div>
<h5>Title:</h5>
<input type="text" value={ this.state.data[0].introTitle } />
<h5>Longtitle:</h5>
<input type="text" value={ this.state.data[0].introLongTitle } />
<h5>Link to video:</h5>
<input type="text" value={ this.state.data[0].videoLink } />
<h5>Text:</h5>
<textarea name="" id="" cols="30" rows="10" value={ this.state.data[0].introText }></textarea>
<button type="submit" className="btn-large waves-effect waves-light xbutton">Save</button>
</form>
);
}
}
export default Misc;
Many many thanks for any help!))
One of the major differences between React and Vue/Angular is the focus on one-way databinding. While you supply a value through state to the input components, they cannot themselves update your state when changes happen.
From the React Docs on Forms:
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We call this controlled components. The component state is the single source of truth, and state can only explicitly be changed by setState. You would typically do this in -- as you said -- a change handler:
class MyForm extends React.Component {
state = {
name: ''
};
handleChange = (evt) => {
// evt is a change event
this.setState({
name: evt.target.value,
});
}
render() {
return (
<input type="text" value={this.state.name} onChange={this.handleChange} />
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
This can of course be cumbersome, especially with many different types of inputs. However it is easy to reason about where changes come from.
You can also use uncontrolled components, where you often supply your inputs with default values. These inputs can change their value, but it will not be reflected in your state. You can use refs to read their value when needed:
class MyForm extends React.Component {
state = {
name: 'Foo'
};
constructor() {
super();
this.inputRef = React.createRef();
}
handleSubmit = (evt) => {
evt.preventDefault();
const name = this.inputRef.current.value;
console.log({ name });
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input ref={this.inputRef} type="text" defaultValue={this.state.name} />
<button type="submit">Submit</button>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Here is how you can do it.
handleChange(key, value){
const data = this.state.data;
data[0][key] = value;
this.setState({data});
}
handleSubmit(){
// You can make post call here.
}
render() {
if (this.state.loading) {
return(
<div>
<p> Loading... </p>
</div>
)
}
if (this.state.error || !this.state.data[0]) { // if request failed or data is empty don't try to access it either
return(
<div>
<p> An error occured </p>
</div>
)
}
return (
<form action="" onSubmit={this.handleSubmit.bind(this)}>
<h2 className="center" >Change data</h2>
<div className="center"><img src={require('../img/orn.png')} alt="" className="orn"/></div>
<h5>Phone:</h5>
<input type="text" value={ this.state.data[0].phone } onChange={this.handleChange.bind(this, "phone")}/>//Here you have to pass key in this case it's phone
<h5>Email:</h5>
<input type="text" value={ this.state.data[0].email } />
<h5>Title:</h5>
<input type="text" value={ this.state.data[0].title }/>
<h5>Longtitle:</h5>
<input type="text" value={ this.state.data[0].longTitle }/>
<h2 className="center" >Intro:</h2>
<div className="center"><img src={require('../img/orn.png')} alt="" className="orn"/></div>
<h5>Title:</h5>
<input type="text" value={ this.state.data[0].introTitle } />
<h5>Longtitle:</h5>
<input type="text" value={ this.state.data[0].introLongTitle } />
<h5>Link to video:</h5>
<input type="text" value={ this.state.data[0].videoLink } />
<h5>Text:</h5>
<textarea name="" id="" cols="30" rows="10" value={ this.state.data[0].introText }></textarea>
<button type="submit" className="btn-large waves-effect waves-light xbutton">Save</button>
</form>
);
}
}
You can more read it on form control https://reactjs.org/docs/forms.html

unable to get enter and get value in REACT.js

I am new to ReactJS and trying to build a sample application
I am unable to get enter the value in textbox and unable to get the value in alert. Am I doing something wrong. I have tried the example given on React.Js Form, but not working.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.value);
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" value={this.state.value} />
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
please change :
<input type="text" value={this.state.value} />
to:
<input type="text" value={this.state.value} onChange = {this.onChange}/>
In your class, add the 'onChange' function:
onChange(e){
this.setState({
value: e.target.value
})
}
and in your constructor:
this.onChange = this.onChange.bind(this)
Edit 1:
please check my codepen here
Edit 2:
If you have too many inputs, you can use a function like this:(it's just a rough example, in real world I'll create a new component to handle this together)
//in your constructor
this.state = {}
//in class 'controlled component way'
createInput(num){
let inputArray = []
for(let i = 0; i < num; i ++){
inputArray.push(<input key = {i} name = {i} onChange = {this.onChange} value = {this.state[i] || ''} />)
}
return inputArray
}
onChange(e){
let key = e.target.name
let newState = {}
newState[key] = e.target.value
this.setState(newState)
}
// in your render function
return <div>
{this.createInput(100)}
</div>
check my codepen here for this example
and of course you can also do this using uncontrolled component.
controlled component and uncontrolled
You can either bind onChange event to your input or setState when submiting the value , you cant change the state like that
Change your code to something like this
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
this.setState({value: this.refs.infield.value},()=>{
alert('name value is : '+this.state.value);
})
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" ref = "infield"/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
Hi to get the value add a name to the input and an onChange function to set the value to the state and then do what evere you want in onsubmit function
I cant write you a working code now because I'm using my phone but my this Will help
onfieldchange(e) {
this.setState({[e.target.name]: e.target.value});
}
onaSubmit(){
//do your code here
}
....
....
<input type="text" name="firstName" value={this.state.firstName} />
Hope this help you
There are two ways to handle form elements in reactjs:
Controlled and uncontrolled components(using refs).In controlled component approach ,you have to add the state of the input field to the input field value and onChange event to it, which is the one you are trying to do.Here is the working code.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {
firstname:''
};
this.OnSubmit = this.OnSubmit.bind(this);
this.OnChange = this.OnChange.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.firstname);
event.preventDefault();
}
OnChange(){
this.setState({
[e.target.name] : [e.target.value]
});
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text"
name="firstname"
value={this.state.firstname}
OnChange={this.OnChange}
/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;

react bootstrap table not rendering data without refresh

i am using react-redux with react bootstrap table . my UI is given in picture . when i add payment the data is saved in database. i have used componentdidupdate and componentdidUpdate to render the props data . but nothing is working . the table does not render the data without refresh . please help......................................................................................................
import React from 'react';
import { connect } from 'react-redux';
// import {bindActionCreators} from 'redux'
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getCrmOneCustomer, saveStatus, getCrmStatus } from '../../actions/crmAction';
//--------------------------------------------------------------------------
class CrmStatus extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '', shop_name: '', crm_id: '', status: ''
};
this.props.dispatch(getCrmOneCustomer(this.props.params.id));
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.props.dispatch(getCrmStatus(this.props.params.id));
}
//--------------------------------------------------------------------------
componentWillReceiveProps(newProps) {
console.log('componentWillReceiveProps............ from edit');
console.log(newProps)
this.setState({
name: newProps.CrmOne.name,
shop_name: newProps.CrmOne.shop_name,
status: newProps.CrmOne.status,
})
}
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleSubmit(event) {
event.preventDefault();
var Id = this.props.params.id;
var obj = {};
obj["crm_id"] = Id
obj["name"] = this.state.name
obj["shop_name"] = this.state.shop_name
obj["status"] = this.state.status
console.log(obj)
this.props.dispatch(saveStatus(obj))
}
//--------------------------------------------------------------------------
componentDidUpdate(){
this.products = this.props.CrmOneStatus
}
render() {
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2>CRM Status</h2>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className ="col-md-8">
<BootstrapTable data={this.products} striped hover pagination={true} search>
<TableHeaderColumn isKey dataField='name'>Name</TableHeaderColumn>
<TableHeaderColumn dataField='status'>status</TableHeaderColumn>
<TableHeaderColumn dataField='createdAt'>Date</TableHeaderColumn>
</BootstrapTable>
</div>
<div className ="col-md-4">
<h4> Add Payment </h4>
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<div className="form-group">
<label>
Name:
</label>
<input disabled type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" />
</div>
<div className="form-group">
<label>
shop name:
</label>
<input type="text" className="form-control" name="shop_name" value={this.state.shop_name} onChange={this.handleChange} placeholder="amount" />
</div>
<div className="form-group">
<label>
Status:
</label>
<textarea rows="8" cols="50" type="text" className="form-control" name="status" value={this.state.status} onChange={this.handleChange} placeholder="comment" />
</div>
<div className="btn-group" role="group">
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
return {
CrmOne: state.crmCustomer.CrmOne,
CrmOneStatus: state.crmCustomer.CrmOneStatus
};
};
export default connect(mapStateToProps)(CrmStatus);
You are making a request to fetch the data in the componentDidMount function which is only executed once when the component has mounted, i.e the reason it works when you refresh the page, However you should get the data whenever the props change, i.e. use the componentWillReceiveProps function. Also you don't need to assign the props to the class variable, you can directly use the props to as data.
class CrmStatus extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '', shop_name: '', crm_id: '', status: ''
};
this.props.dispatch(getCrmOneCustomer(this.props.params.id));
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.props.dispatch(getCrmStatus(this.props.params.id));
}
componentWillReceiveProps(newProps) {
console.log('componentWillReceiveProps............ from edit');
console.log(newProps)
if(nextProps.params.id !== this.props.params.id) {
this.props.dispatch(getCrmStatus(nextProps.params.id));
}
this.setState({
name: newProps.CrmOne.name,
shop_name: newProps.CrmOne.shop_name,
status: newProps.CrmOne.status,
})
}
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleSubmit(event) {
event.preventDefault();
var Id = this.props.params.id;
var obj = {};
obj["crm_id"] = Id
obj["name"] = this.state.name
obj["shop_name"] = this.state.shop_name
obj["status"] = this.state.status
console.log(obj)
this.props.dispatch(saveStatus(obj))
}
//--------------------------------------------------------------------------
render() {
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2>CRM Status</h2>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className ="col-md-8">
<BootstrapTable data={this.props.CrmOneStatus} striped hover pagination={true} search>
<TableHeaderColumn isKey dataField='name'>Name</TableHeaderColumn>
<TableHeaderColumn dataField='status'>status</TableHeaderColumn>
<TableHeaderColumn dataField='createdAt'>Date</TableHeaderColumn>
</BootstrapTable>
</div>
<div className ="col-md-4">
<h4> Add Payment </h4>
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<div className="form-group">
<label>
Name:
</label>
<input disabled type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" />
</div>
<div className="form-group">
<label>
shop name:
</label>
<input type="text" className="form-control" name="shop_name" value={this.state.shop_name} onChange={this.handleChange} placeholder="amount" />
</div>
<div className="form-group">
<label>
Status:
</label>
<textarea rows="8" cols="50" type="text" className="form-control" name="status" value={this.state.status} onChange={this.handleChange} placeholder="comment" />
</div>
<div className="btn-group" role="group">
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
in constructor i added this
this.props.dispatch(getCrmStatus(this.props.params.id));
and handle submit
this.props.dispatch(getCrmStatus(this.props.params.id));
and it works like charm !!!!!!!!!!!!!!

Unable to type in input after adding value in React Js

I have tried with the following code with react js
import React, { Component } from 'react';
import Sidebar from './../Sidebar';
import Header from './../Header';
import {get_profile} from './../services/Services';
import $ from 'jquery';
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = { userDetails: '' } ;
}
componentWillMount() {
$(window).scrollTop(0)
console.log('sdfds')
get_profile().then((response) => {
var userResults = $.parseJSON(response.text);
this.setState({ userDetails: userResults.response });
console.log(userResults);
}).catch((error) => {
//alert(error)
console.log(error);
});
}
handleChange(event) {
console.log(event.target.id)
this.setState({[event.target.name]: event.target.value});
}
render() {
return (
<div className="admin-panel">
<Sidebar />
<Header />
<div className="main-content">
<div className="contents">
<div className="container-fluid">
<div className="row">
<div className="col-sm-6">
<h2 className="page-title">Profile</h2>
<div className="form-group">
<label >First Name</label>
<input type="text" id="firstName" className="form-control" value={this.state.userDetails.firstName} />
</div>
<div className="form-group">
<label >Last Name</label>
<input type="text" id="lastName" className="form-control" value={this.state.userDetails.lastName} />
</div>
<div className="form-group">
<label >Email</label>
<input type="text" id="email" name="email" className="form-control" value={this.state.userDetails.email} />
</div>
<button type="button" className="btn btn-squared btn-success margin-inline" onClick={(e)=> {this.profileUpdate()}}>Update</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
After fetching the results i'm unable to edit the input box value. I have tried with defaultValue but that also not working for me. I'm struck with this issue, Kindly help me to solve the issue.
Just pass an onChange handler to the input which will update the value of the corresponding key of userDetails like this:
<input
...
value={this.state.userDetails.firstName}
onChange={this.onChange}
/>
onChange(e) {
this.setState((previousState) => {
const userDetails = previousState.userDetails
return { userDetails: {...userDetails, firstName: e.target.value} }
})
}
or you can write a common onChange function like this:
<input
...
value={this.state.userDetails.firstName}
onChange={(e) => {this.onChange(e.target.value, 'firstName')}}
/>
<input
...
value={this.state.userDetails.lastName}
onChange={(e) => {this.onChange(e.target.value, 'lastName')}}
/>
<input
...
value={this.state.userDetails.email}
onChange={(e) => {this.onChange(e.target.value, 'email')}}
/>
onChange(value, key) {
this.setState((previousState) => {
const userDetails = previousState.userDetails
return { userDetails: {...userDetails, [key]: value} }
})
}

Resources