I am creating a form component and I want to be able to pass on change elements per form element and I cannot seem to get it work properly.
I have my LoginComponent
import React from "react";
import './LoginComponent.css';
import FormComponent from '../FormComponent/FormComponent';
class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Login",
id: "login-form",
name: "login-form",
items: [
{
element: "input",
type: "email",
id: "lf-email",
name: "lf-email",
value: "",
onChange: this.handleOnChangeEmail.bind(this),
placeholder: "Email",
img: {},
},
{
element: "input",
type: "password",
id: "lf-password",
name: "lf-password",
value: "",
onChange: ,
placeholder: "Password",
img: {},
},
{
element: "checkbox",
id: "lf-remember-me",
name: "lf-remember-me",
value: "lf-remember-me",
onChange: ,
display: "Remember Me",
isSelected: false
}
]
}
}
// Figure out how to pass onChange functions per item in state.
handleOnChangeEmail(e) {
console.log("Email changed");
}
render() {
return (
<div className="LoginComponent">
{/*
Create onSubmit function for submitting the form
Create handle change functions for inputs
*/}
<FormComponent id={ this.state.id } name={ this.state.name } onSubmit="" header={ this.state.header } items={ this.state.items } />
</div>
);
}
}
export default LoginComponent;
As you can see I want to pass in the handle function in the state of the component so I can uniquely handle form inputs. When I run this code though it fails because I cannot pass a function in the state. Is this type of request allowed or able to accomplish in another way?
I know you can pass the bound function to the component directly but the form component is dynamically built based on the state.item array.
Here is my form component
import React from "react";
import './FormComponent.css';
import InputComponent from './InputComponent/InputComponent';
import FormHeaderComponent from './FormHeaderComponent/FormHeaderComponent';
import CheckboxComponent from "./CheckboxComponent/CheckboxComponent";
class FormComponent extends React.Component {
render() {
const formItems = this.props.items.map((item) => {
switch(item.element) {
case "input":
return <InputComponent type={ item.type } id={ item.id } name={ item.name } placeholder={ item.placeholder } value={ item.value } onChange={ item.onChange } />
case "checkbox":
return <CheckboxComponent id={ item.id } name={ item.name } value={ item.value } selected={ item.isSelected } onChange={ item.onChange } display={ item.display } />
default:
return <InputComponent />;
}
});
return (
<form id={ this.props.id } name={ this.props.name }>
<FormHeaderComponent header={ this.props.header } />
{/*
Setup handling of submit functions
Setup handling of onchange function for inputs
*/}
{ formItems }
</form>
);
}
}
export default FormComponent;
As you can see in the formItems I am trying to create the elements with the onChange function from the state passed in. Any help or suggestions would be appreciated. I am well aware also I can just make the form component a component that loads all children passed so you basically build the form in the login component without state but I would prefer that not be the case.
Storing methods in state to be passed to children is usually a bad idea. I propose an alternative.
Consider the onChange function, that will still reside in LoginComponent and will be passed as a prop to the <FormComponent />
The handler is written as such that you'll be able to identify which child component called it, by taking it's name attribute too, eliminating the need to make a unique handler for each input.
LoginComponent:
handleOnChangeEmail(e) {
const { name, value } = e.target;
console.log(`${name} changed to ${value}`);
}
render() {
return (
<div className="LoginComponent">
<FormComponent
id={this.state.id}
name={this.state.name}
onSubmit=""
header={this.state.header}
items={this.state.items}
formOnChange={this.handleOnChangeEmail}
/>
</div>
);
}
Then when you are iterating over and constructing your InputComponent, pass this to it's onChange:
FormComponent:
class FormComponent extends React.Component {
render() {
const formItems = this.props.items.map(item => {
switch (item.element) {
case "input":
return (
<InputComponent
type={item.type}
id={item.id}
name={item.name}
placeholder={item.placeholder}
value={item.value}
onChange={this.props.formOnChange}
/>
);
case "checkbox":
return (
<CheckboxComponent
id={item.id}
name={item.name}
value={item.value}
selected={item.isSelected}
onChange={this.props.formOnChange}
display={item.display}
/>
);
default:
return <InputComponent />;
}
});
return (
<form id={this.props.id} name={this.props.name}>
<FormHeaderComponent header={this.props.header} />
{formItems}
</form>
);
}
}
PS: Don't forget to bind your functions or use arrow functions.
Try implementing same function handleChange to handle all form value change.
React onChange function pass event argument. With event argument perform necessary logic. Do not need onChange key in form object in state.
// use lodash library for array handling.
// yarn add lodash
// import {indexOf} from "lodash"
// using fat arrow will save from binding function in constructor.
handleChange=({target})=> {
const {items} = this.state;
// target.name/id will give the element state can be update as required.
let index = indexOf(items, {name:target.name})
items[index].value = target.value;
this.setState({
items
})
}
// remove handle change from items and just user it for all form value change.
<FormComponent id={ this.state.id } name={ this.state.name } handleChange={this.handleChange} onSubmit="" header={ this.state.header } items={ this.state.items } />
Related
I am new to React and Javascript.
I am trying to have a user fill in a form that describes what a "Mob" should look like. When the user hits submit, I expect handleSubmit() (passed in through a parent) to modify the parent's state, which is an object. However, this behavior is not happening.
Here is the parent component, called App.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
mob: new Mob("", "")
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
alert("A name was submitted: " + this.state.vnum + " event value: " + event.state.vnum);
const newMob = new Mob(event.state.vnum, event.state.shortDesc);
this.setState({
mob: newMob
});
}
render() {
return (
<div>
<MobForm mob={this.state.mob} onSubmit={() => this.handleSubmit} />
{console.log("parsed mob vnum: " + this.state.mob.vnum)}
</div>
);
}
}
The child component, called MobForm
class MobForm extends React.Component {
render() {
return (
<div>
<form onSubmit={this.props.onSubmit}>
<CreateStringInputField
name="vnum"
label="vnum:"
/>
<CreateStringInputField
name="shortDesc"
label="Short Desc:"
/>
<input type="submit" value="Submit" />
</form>
{console.log(this.state)}
</div>
);
}
}
Which is calling CreateStringInputField()
function CreateStringInputField(props) {
return (
<div name="row">
<label>
<b>{props.label}</b>
<br />
<input
type="text"
name={props.name}
label={props.label}
/>
</label>
</div>
);
}
And, in case it matters, here is what "Mob" looks like.
class Mob {
constructor(vnum, shortDesc) {
this.vnum = vnum;
this.shortDesc = shortDesc;
};
}
I expect to see {console.log("parsed mob vnum: " + this.state.mob.vnum)} print out the vnum as entered by a user. Instead, I see nothing. How can I achieve this expected output?
With React you won't need to work with plain classes. Instead, the class extends a provided React component (Component or PureComponent) or if you don't need state, then'll use plain functions that just return some JSX.
Working example: https://codesandbox.io/s/simple-form-kdh3w
index.js
import React from "react";
import { render } from "react-dom";
import MobForm from "./components/MobForm";
// simple function that returns "MobForm" and it gets rendered by ReactDOM
function App() {
return <MobForm />;
}
// applies "App" to a <div id="root"></div> in the public/index.html file
render(<App />, document.getElementById("root"));
components/MobForm/index.js (stateful parent component)
import React, { Component } from "react";
import Form from "../Form";
const initialState = {
vnum: "",
shortDesc: ""
};
// a stateful parent that manages child state
class MobForm extends Component {
constructor(props) {
super(props);
this.state = initialState;
// since the class fields are normal functions, they'll lose context
// of "this" when called as a callback. therefore, they'll need
// to be bound to "this" -- via bind, "this" is now referring to
// the Class, instead of the global window's "this")
this.handleChange = this.handleChange.bind(this);
this.handleReset = this.handleReset.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// a reusable class field that stores an input's value via its "name"
// for example: [vnum]: "12345", [shortDesc]: "A number"
// using object destructuring for shorter syntax:
// [event.target.name]: event.target.value
handleChange({ target: { name, value } }) {
this.setState({ [name]: value });
}
// a class field to reset state
handleReset() {
this.setState(initialState);
}
// a class field to "submit" the form and alert what's currently in state
handleSubmit(event) {
// preventDefault prevents page refreshes
event.preventDefault();
// JSON.stringify allows you to print the contents of an object
// otherwise, you'll just see [object Object]
alert(JSON.stringify(this.state, null, 4));
// clears state after submitting form
this.handleReset();
}
render() {
return (
// passing down state via the spread operator, shorthand for
// "vnum={this.state.vum}" and "shortDesc={this.state.shortDesc}",
// as well as, passing down the class fields from above
<Form
{...this.state}
handleChange={this.handleChange}
handleReset={this.handleReset}
handleSubmit={this.handleSubmit}
/>
);
}
}
export default MobForm;
components/Form/index.js (a child function that returns some form JSX)
import React from "react";
import PropTypes from "prop-types";
import Input from "../Input";
// using object destructuring to pull out the MobForm's passed down
// state and fields. shorthand for using one parameter named "props"
// and using dot notation: "props.handleChange", "props.handleReset", etc
function Form({ handleChange, handleReset, handleSubmit, shortDesc, vnum }) {
return (
<form style={{ width: 200, margin: "0 auto" }} onSubmit={handleSubmit}>
<Input name="vnum" label="vnum:" value={vnum} onChange={handleChange} />
<Input
name="shortDesc"
label="Short Desc:"
value={shortDesc}
onChange={handleChange}
/>
<button type="button" onClick={handleReset}>
Reset
</button>{" "}
<button type="submit">Submit</button>
</form>
);
}
// utilizing "PropTypes" to ensure that passed down props match
// the definitions below
Form.propTypes = {
handleChange: PropTypes.func.isRequired,
handleReset: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
shortDesc: PropTypes.string,
vnum: PropTypes.string
};
export default Form;
components/Input/index.js (a reuseable input function)
import React from "react";
import PropTypes from "prop-types";
// once again, using object destructuring to pull out the Form's
// passed down state and class fields.
function Input({ label, name, value, onChange }) {
return (
<div name="row">
<label>
<b>{label}</b>
<br />
<input
type="text"
name={name}
label={label}
value={value}
onChange={onChange}
/>
</label>
</div>
);
}
// utilizing "PropTypes" to ensure that passed down props match
// the definitions below
Input.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
value: PropTypes.string,
onChange: PropTypes.func.isRequired
};
export default Input;
In this line
<MobForm mob={this.state.mob} onSubmit={() => this.handleSubmit} />
you are defining an anonymous function that returns your handleSubmit function.
In your form
<form onSubmit={this.props.onSubmit}>
onSubmit will execute the this.props.onSubmit which just returns the handleSubmit function but it wont execute it. To fix it just change MobForm to pass handleSubmit directly instead of passing it in an anonymous function:
<MobForm mob={this.state.mob} onSubmit={this.handleSubmit} />
To handle the submission correctly you need to convert your form inputs to managed components. See docs here
Something like this would be a good start:
class MobForm extends React.Component {
constructor(props) {
super(props);
this.state = {
vnum: '',
shortDesc: '',
};
this.handleChangeVnum = this.handleChangeVnum.bind(this);
this.handleChangeShortDesc = this.handleChangeShortDesc.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChangeVnum(event) {
this.setState({vnum: event.target.value});
}
handleChangeShortDesc(event) {
this.setState({shortDesc: event.target.value});
}
handleSubmit(event) {
this.props.onSubmit(this.state);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<CreateStringInputField
name="vnum"
label="vnum:"
value={this.state.vnum}
onChange={this.handleChangeVnum}
/>
<CreateStringInputField
name="shortDesc"
label="Short Desc:"
value={this.state.shortDesc}
onChange={this.handleChangeShortDesc}
/>
<input type="submit" value="Submit" />
</form>
{console.log(this.state)}
</div>
);
}
}
And update CreateStringInputField()
function CreateStringInputField(props) {
return (
<div name="row">
<label>
<b>{props.label}</b>
<br />
<input
type="text"
name={props.name}
label={props.label}
value={props.value}
onChange={props.onChange}
/>
</label>
</div>
);
}
I was able to get my desired behavior by passing a function to MobForm which updates this.state.mob.
App
class App extends React.Component {
state = {
mob: new Mob("", "")
};
updateMob = newMob => {
this.setState({
mob: newMob
});
};
render() {
return (
<div>
<MobForm mob={this.state.mob} onSubmit={this.updateMob} />
</div>
);
}
}
I then made MobForm maintain vnum, shortDesc state that I could use in my onChange()
MobForm
state = { vnum: "", shortDesc: "" };
handleSubmit = event => {
event.preventDefault();
const mob = new Mob(this.state.vnum, this.state.shortDesc);
this.props.onSubmit(mob);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<CreateStringInputField
name="vnum"
value={this.state.vnum}
onChange={event => this.setState({ vnum: event.target.value })}
/>
<CreateStringInputField
name="short desc"
value={this.state.shortDesc}
onChange={event => this.setState({ shortDesc: event.target.value })}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
Im making my first react project. Im new in JS, HTML, CSS and even web app programming.
What i want to do it is a Search input label. Now its look like this:
Like you can see i have some list of objects and text input.
I Have two components, my ProjectList.js with Search.js component...
class ProjectsList extends Component {
render() {
return (
<div>
<Search projects={this.props.projects} />
<ListGroup>
{this.props.projects.map(project => {
return <Project project={project} key={project.id} />;
})}
</ListGroup>
</div>
);
}
}
export default ProjectsList;
... and ProjectList.js displays Project.js:
How looks Search.js (its not ended component)
class Search extends Component {
state = {
query: ""
};
handleInputChange = () => {
this.setState({
query: this.search.value
});
};
render() {
return (
<form>
<input
ref={input => (this.search = input)}
onChange={this.handleInputChange}
/>
<p />
</form>
);
}
}
export default Search;
My project have name property. Could you tell me how to code Search.js component poperly, to change displaying projects dynamically based on input in text label? for example, return Project only, if text from input match (i want to search it dynamically, when i start typing m... it shows all projects started on m etc).
How to make that Search input properly? How to make it to be universal, for example to Search in another list of objects? And how to get input from Search back to Parent component?
For now, in react dev tools whatever i type there i get length: 0
Thanks for any advices!
EDIT:
If needed, my Project.js component:
class Project extends Component {
state = {
showDetails: false
};
constructor(props) {
super(props);
this.state = {
showDetails: false
};
}
toggleShowProjects = () => {
this.setState(prevState => ({
showDetails: !prevState.showDetails
}));
};
render() {
return (
<ButtonToolbar>
<ListGroupItem className="spread">
{this.props.project.name}
</ListGroupItem>
<Button onClick={this.toggleShowProjects} bsStyle="primary">
Details
</Button>
{this.state.showDetails && (
<ProjectDetails project={this.props.project} />
)}
</ButtonToolbar>
);
}
}
export default Project;
To create a "generic" search box, perhaps you could do something like the following:
class Search extends React.Component {
componentDidMount() {
const { projects, filterProject, onUpdateProjects } = this.props;
onUpdateProjects(projects);
}
handleInputChange = (event) => {
const query = event.currentTarget.value;
const { projects, filterProject, onUpdateProjects } = this.props;
const filteredProjects = projects.filter(project => !query || filterProject(query, project));
onUpdateProjects(filteredProjects);
};
render() {
return (
<form>
<input onChange={this.handleInputChange} />
</form>
);
}
}
This revised version of Search takes some additional props which allows it to be reused as required. In addition to the projects prop, you also pass filterProject and onUpdateProjects callbacks which are provided by calling code. The filterProject callback allows you to provide custom filtering logic for each <Search/> component rendered. The onUpdateProjects callback basically returns the "filtered list" of projects, suitable for rendering in the parent component (ie <ProjectList/>).
The only other significant change here is the addition of visibleProjects to the state of <ProjectList/> which tracks the visible (ie filtered) projects from the original list of projects passed to <ProjectList/>:
class Project extends React.Component {
render() {
return (
<div>{ this.props.project }</div>
);
}
}
class ProjectsList extends React.Component {
componentWillMount() {
this.setState({ visibleProjects : [] })
}
render() {
return (
<div>
<Search projects={this.props.projects} filterProject={ (query,project) => (project == query) } onUpdateProjects={ projects => this.setState({ visibleProjects : projects }) } />
<div>
{this.state.visibleProjects.map(project => {
return <Project project={project} key={project.id} />;
})}
</div>
</div>
);
}
}
class Search extends React.Component {
componentDidMount() {
const { projects, filterProject, onUpdateProjects } = this.props;
onUpdateProjects(projects);
}
handleInputChange = (event) => {
const query = event.currentTarget.value;
const { projects, filterProject, onUpdateProjects } = this.props;
const filteredProjects = projects.filter(project => !query || filterProject(query, project));
onUpdateProjects(filteredProjects);
};
render() {
return (
<form>
<input onChange={this.handleInputChange} />
</form>
);
}
}
ReactDOM.render(
<ProjectsList projects={[0,1,2,3]} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
I will assumes both your Search and ProjectList component have a common parent that contains the list of your projects.
If so, you should pass a function into your Search component props, your Search component will then call this function when the user typed something in the search bar. This will help your parent element decide what your ProjectsLists needs to render :
handleInputChange = () => {
this.props.userSearchInput(this.search.value);
this.setState({
query: this.search.value
});
};
And now, here is what the parent element needs to include :
searchChanged = searchString => {
const filteredProjects = this.state.projects.filter(project => project.name.includes(searchString))
this.setState({ filteredProjects })
}
With this function, you will filter out the projects that includes the string the user typed in their names, you will then only need to put this array in your state and pass it to your ProjectsList component props
You can find the documentation of the String includes function here
You can now add this function to the props of your Search component when creating it :
<Search userSearchInput={searchChanged}/>
And pass the filtered array into your ProjectsList props :
<ProjectsList projects={this.state.filteredProjects}/>
Side note : Try to avoid using refs, the onCHnage function will send an "event" object to your function, containing everything about what the user typed :
handleInputChange = event => {
const { value } = event.target
this.props.userSearchInput(value);
this.setState({
query: value
});
};
You can now remove the ref from your code
I have the following problem.
I have customized my own DropDown component using elements.
I want this element to interact with Redux-Form as I want to save the value that is selected.
This does not work:
<Field
name="name"
component={MyCustomizedDropDown}
data={myData}/>
The other option was to use the "input" props but as I am using elements, this is not possible.
Can someone give me a solution? Thanks.
MyCustomizedDropDown component:
import React, { Component } from "react";
import PropTypes from "prop-types";
class MyCustomizedDropdown extends Component {
constructor(props) {
super(props);
this.state = {
...this.props,
items: this.props.items || [],
selectedItem: this.props.items[0] || this.props.selectedItem,
showItems: false,
isOpened: false
};
this.dropDown = this.dropDown.bind(this);
this.selectedItem = this.selectedItem.bind(this);
}
dropDown() {
this.setState(prevState => ({
showItems: !prevState.showItems
}));
}
selectedItem(item) {
this.setState({
selectedItem: item,
showItems: false
});
}
render() {
const { input } = this.props;
return (
<div className="select-box--wrapper">
<div className="select-box--toggle" onClick={this.dropDown}>
<div className="select-box--selected-item">
{this.state.selectedItem && this.state.selectedItem.value}
</div>
<MyImage
className={`${
this.state.showItems
? "select-box--arrow-rotated"
: "select-box--arrow"
}`}
/>
</div>
<div className="select-box--main">
<div
{...input} \\THIS DOES NOT WORK
className="select-box--items">
{this.state.data.map(item => (
<div key={item.id} onClick={() => this.selectedItem(item)}>
{item.value}
</div>
))}
</div>
</div>
</div>
);
}
}
MyCustomizedDropdown.propTypes = {
data: PropTypes.array,
selectedItem: PropTypes.array,
input: PropTypes.object
};
export default MyCustomizedDropdown;
redux-form only works with "controlled" components. That means the component needs a prop that a parent uses to tell it what it's value is. For example, the following is a controlled component:
<TextField
value={this.state.inputValue}
onChange={(value) => this.setState({ inputValue: value })}
/>
Note that we're telling the TextField component what it's value is. You need to change your component to work the same way. The only caveat here is that redux-form injects a prop called input that is an object containing value and onChange (and a few other things), instead of directly injecting value and onChange.
So for the example above, it needs to work like this to support redux-form:
<TextField
input={{
value: this.state.inputValue,
onChange: (value) => this.setState({ inputValue: value })
}}
/>
Here's your component written as a "controlled" component, in a way that should work with redux-form:
import React, { Component } from "react";
import PropTypes from "prop-types";
class MyCustomizedDropdown extends Component {
constructor(props) {
super(props);
this.state = {
showItems: false
};
this.dropDown = this.dropDown.bind(this);
this.selectedItem = this.selectedItem.bind(this);
}
dropDown() {
this.setState(prevState => ({
showItems: !prevState.showItems
}));
}
hideDropdownItems() {
this.setState({
showItems: false
});
}
render() {
const { input } = this.props;
return (
<div className="select-box--wrapper">
<div className="select-box--toggle" onClick={this.dropDown}>
<div className="select-box--selected-item">
{this.input.value && this.input.value.value}
</div>
<MyImage
className={`${
this.state.showItems
? "select-box--arrow-rotated"
: "select-box--arrow"
}`}
/>
</div>
<div className="select-box--main">
<div
className="select-box--items">
{this.state.data.map(item => (
<div
key={item.id}
onClick={() => {
this.input.onChange(item)
this.hideDropdownItems();
}}
>
{item.value}
</div>
))}
</div>
</div>
</div>
);
}
}
MyCustomizedDropdown.propTypes = {
data: PropTypes.array,
selectedItem: PropTypes.array,
input: PropTypes.object
};
export default MyCustomizedDropdown;
Note we tell MyCustomizedDropdown what it's value is using this.props.input.value
We call this.props.input.onChange if the component wants to change it's value. Since it can't do it on it's own, it needs to tell it's parent it wants to change value.
The parent needs to respond to onChange and update MyCustomizedDropdown's value
For example, this is how you'd use your component without redux-form:
<MyCustomizedDropdown
input={{
value: this.state.dropDownValue,
onChange: (value) => this.setState({ dropDownValue: value })
}}
/>
And with redux-form, you can simply do the following, since redux-form manages all that stuff for you:
<Field
component={MyCustomizedDropdown}
/>
You shouldn't be handling the value of the input in the input's state. MyCustomizedDropDown should receive the handleChange function, items and selectedItem as props. The only thing that should be in the component's state is it's open or not.
The InputField & Button are custom components that go into a form to create a form. My issue is how do I send the data back up to form so that on button click, I can fire ajax on the form with data (username & password):
export default auth.authApi(
class SignUpViaEmail extends Component{
constructor(props){
super(props);
this.state = {
email : "",
password : ""
};
this.storeEmail = this.storeEmail.bind( this );
this.storePassword = this.storePassword.bind( this );
}
storeEmail(e){
this.setState({ email : e.target.value });
}
storePassword(e){
this.setState({ password : e.target.value });
}
handleSignUp(){
this.props.handleSignUp(this.state);
}
render(){
return(
<div className="pageContainer">
<form action="" method="post">
<InputField labelClass = "label"
labelText = "Username"
inputId = "signUp_username"
inputType = "email"
inputPlaceholder = "registered email"
inputClass = "input" />
<Button btnClass = "btnClass"
btnLabel = "Submit"
onClickEvent = { handleSignUp } />
</form>
</div>
);
}
}
);
Or Is it not recommended & I should not create custom child components within the form?
child component => InputField
import React,
{ Component } from "react";
export class InputField extends Component{
constructor( props ){
super( props );
this.state = {
value : ""
};
this.onUserInput = this.onUserInput.bind( this );
}
onUserInput( e ){
this.setState({ value : e.target.value });
this.props.storeInParentState({[ this.props.inputType ] : e.target.value });
}
render(){
return <div className = "">
<label htmlFor = {this.props.inputId}
className = {this.props.labelClass}>
{this.props.labelText}
</label>
<input id = {this.props.inputId}
type = {this.props.inputType}
onChange = {this.onUserInput} />
<span className = {this.props.validationClass}>
{ this.props.validationNotice }
</span>
</div>;
}
}
Error : I get the error e.target is undefined on the parent storeEmail func.
React's one-way data-binding model means that child components cannot send back values to parent components unless explicitly allowed to do so. The React way of doing this is to pass down a callback to the child component (see Facebook's "Forms" guide).
class Parent extends Component {
constructor() {
this.state = {
value: ''
};
}
//...
handleChangeValue = event => this.setState({value: event.target.value});
//...
render() {
return (
<Child
value={this.state.value}
onChangeValue={this.handleChangeValue}
/>
);
}
}
class Child extends Component {
//...
render() {
return (
<input
type="text"
value={this.props.value}
onChange={this.props.onChangeValue}
/>
);
}
}
Take note that the parent component handles the state, while the child component only handles displaying. Facebook's "Lifting State Up" guide is a good resource for learning how to do this.
This way, all data lives within the parent component (in state), and child components are only given a way to update that data (callbacks passed down as props). Now your problem is resolved: your parent component has access to all the data it needs (since the data is stored in state), but your child components are in charge of binding the data to their own individual elements, such as <input> tags.
Addendum
In response to this comment:
What if we render a list of the child component? Using this single source of truth in Lifting state up technique will let the parent controls all the state of all the child inputs right? So how can we access each of the value input in the child component to (which is rendered as list) from the parent component?
For this case, you may map a child component for each element in the list. For example:
class Parent extends Component {
//...
handleChangeListValue = index => event => {
this.setState({
list: this.state.list
.map((element, i) => i === index ? event.target.value : element)
});
}
//...
render() {
return this.state.list.map((element, i) => (
<Child
value={element}
onChangeValue={this.handleChangeListValue(i)}
/>
));
P.S. Disclaimer: above code examples are only for illustrative purposes of the concept in question (Lifting State Up), and reflect the state of React code at the time of answering. Other questions about the code such as immutable vs mutable array updates, static vs dynamically generated functions, stateful vs pure components, and class-based vs hooks-based stateful components are better off asked as a separate question altogether.
React class component
Parent.js
import React, { Component } from 'react';
import Child from './child'
class Parent extends Component {
state = {
value: ''
}
onChangeValueHandler = (val) => {
this.setState({ value: val.target.value })
}
render() {
const { value } = this.state;
return (
<div>
<p> the value is : {value} </p>
<Child value={value} onChangeValue={this.onChangeValueHandler} />
</div>
);
}
}
export default Parent;
Child.js
import React, { Component } from 'react';
class Child extends Component {
render() {
const { value , onChangeValue } = this.props;
return (
<div>
<input type="text" value={value} onChange={onChangeValue}/>
</div>
);
}
}
export default Child;
React hooks
Parent.js
import { useState } from "react";
import Child from "./child";
export default function Parent() {
const [value, changeValue] = useState("");
return (
<div>
<h1>{value}</h1>
<Child inputValue={value} onInputValueChange={changeValue} />
</div>
);
}
Child.js
export default function Child(props) {
return (
<div>
<input
type="text"
value={props.inputValue}
onChange={(e) => props.onInputValueChange(e.target.value)}/>
</div>
);
}
Parent.js
import SearchBar from "./components/SearchBar";
function App() {
const handleSubmit = (term) => {
//Log user input
console.log(term);
};
return (
<div>
<SearchBar onPressingEnter={handleSubmit} />
</div>
);
}
export default App;
Child.js
import { useState } from "react";
function SearchBar({ onPressingEnter }) {
const [UserSearch, setname] = useState("[]");
/* The handleChange() function to set a new state for input */
const handleChange = (e) => {
setname(e.target.value);
};
const onHandleSubmit = (event) => {
//prevent form from making a http request
event.preventDefault();
onPressingEnter(UserSearch);
};
return (
<div>
<form onSubmit={onHandleSubmit}>
<input
type="search"
id="mySearch"
value={UserSearch}
onChange={handleChange}
name="q"
placeholder="Search the siteā¦"
required
/>
</form>
</div>
);
}
export default SearchBar;
You can add a "ref name" in your InputField so you can call some function from it, like:
<InputField
ref="userInput"
labelClass = "label"
labelText = "Username"
inputId = "signUp_username"
inputType = "email"
inputPlaceholder = "registered email"
inputClass = "input" />
So you can access it using refs:
this.refs.userInput.getUsernamePassword();
Where getUsernamePassword function would be inside the InputField component, and with the return you can set the state and call your props.handleSignUp
I have some Card (more than 10 Card component) in a Cards component and each Card has a form with more than 10 textField components. When I'm typing in textFields, It has delay between type and update value of textField. After spending more than 2 days, I found my problem. I think it's related to re-rendering all Childs (all Card components) when I set my value in statein value update... .
I want to know where am I wrong? If my codes is standard, is there any way to stop re-rendering all Childs after changing state for just one textField?
My codes are like as follow:
MainComponent:
export default class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {
value : {}
};
}
static PropTypes = {
results: PropTypes.array.isRequired
};
handleChange(ref, e) {
this.state.value[ref] = e;
this.setState(this.state);
}
render() {
const { results } = this.props;
<Cards>
{
results.map((result, index) => {
var ref_taxtfield1 = result.id + "taxtfield1";
var ref_taxtfield2 = result.id + "taxtfield2";
var ref_taxtfield3 = result.id + "taxtfield3";
var ref_taxtfield4 = result.id + "taxtfield4";
var ref_taxtfield5 = result.id + "taxtfield5";
return <Card key={ result.id } style={ styles.card }>
<Form>
<div style={ styles.innerContainer }>
<Textfield
name="taxtfield1"
label="My Label 1"
ref={ref_taxtfield1}
onValueChange={this.handleChange.bind(this, ref_taxtfield1)}
value={this.state.value[ref_taxtfield1]}
/>
<Textfield
name="taxtfield2"
label="My Label 2"
ref={ref_taxtfield2}
onValueChange={this.handleChange.bind(this, ref_taxtfield2)}
value={this.state.value[ref_taxtfield2]}
/>
<Textfield
name="taxtfield3"
label="My Label 3"
ref={ref_taxtfield3}
onValueChange={this.handleChange.bind(this, ref_taxtfield3)}
value={this.state.value[ref_taxtfield3]}
/>
<Textfield
name="taxtfield4"
label="My Label 4"
ref={ref_taxtfield4}
onValueChange={this.handleChange.bind(this, ref_taxtfield4)}
value={this.state.value[ref_taxtfield4]}
/>
<Textfield
name="taxtfield5"
label="My Label 5"
ref={ref_taxtfield5}
onValueChange={this.handleChange.bind(this, ref_taxtfield5)}
value={this.state.value[ref_taxtfield5]}
/>
</div>
</Form>
</Card>})}
</Cards>
}
}
My TextField Component
export default class Textfield extends Input {
static defaultProps = {
initialCount: 0,
value: "",
defaultValue: "",
onValueChange: null,
label: ""
};
state = { focused: false };
onChange = this.onChange.bind(this);
onChange(e) {
if(this.props.onValueChange){
this.props.onValueChange(e.target.value);
}
}
handleOnBlur = this.handleOnBlur.bind(this);
handleOnBlur(e){
this.setState({focused: false});
if(this.props.onBlur){
this.props.onBlur(e);
}
}
render() {
const { focused } = this.state;
const { value, disabled } = this.props;
return (
<div>
<label>{this.props.label}</label>
<input
{ ...this.inputProps() }
type="text"
placeholder={this.props.placeholder}
defaultValue={this.props.defaultValue}
onChange={this.onChange}
onBlur={this.handleOnBlur}
value={ isCurrency ? formatData.currency(value) : value}
disabled={disabled}
/>
</div>
)
}
}
My Card and Cards Component
export class Cards extends Component {
render() {
const { children, ...props } = this.props;
return <div {...props} >{ children }</div>;
}
};
export class Card extends Component {
render() {
const { ...props } = this.props;
return <div {...props} } />
}
}
I use ES6 syntax and also remove all style tags from my code to simplify.
You are passing a new function to every Textfield component on render:
onValueChange={this.handleChange.bind(this, ref_taxtfield1)}
.bind returns a new function every time, causing every Textfield to render on each update.
Two possible solutions:
Don't use .bind inside .render. .bind the method once in the constructor and let Textfield pass an identifier to this.props.onValueChange.
Implement shouldComponentUpdate in Textfield, returning false if only this.props.onValueChange changed.