This question already has an answer here:
Update state values with props change in reactjs
(1 answer)
Closed 4 years ago.
I have a main component, and when I pass down a prop to another component, it doesn't update the style. The display is still none, whereas it's meant to update to block since I have changed the prop to true. What might be wrong?
class Apps extends Component {
constructor(props) {
super(props);
// Don't do this!
this.state = { showing: true, Login: false, Signup: false, Members: false };
}
render() {
return (
<div>
<div
className="container"
style={{ display: this.state.showing ? "block" : "none" }}
>
<div>A Single Page web application made with react</div>
</div>
<LoginComponent view={this.state.Login} />
<div className="buttons">
<a href="" ref="login" onClick={this.Login_onclick.bind(this)}>
{this.state.Login ? "back" : "Login"}
</a>
<br />
</div>
</div>
);
}
Login_onclick(e) {
this.setState({ Login: !this.state.Login });
e.preventDefault(); //alert(e.target.value);
this.setState({ showing: !this.state.showing });
// this.setState({ref: !ref});
}
}
Login Component
class LoginComponent extends Component {
constructor(props) {
super(props);
this.state = {
show: this.props.view
};
}
render() {
return (
<div
className="login"
style={{ display: this.state.show ? "block" : "none" }}
>
<h3>Login</h3>
<br />
Username: <input type="text" ref="username" />
<br />
Password <input type="password" ref="password" />
<button value="Login">Login</button>
</div>
);
}
}
You are setting this.state = { show: this.props.view }; when the component is created. Changing the view prop after that will have no effect.
There is no need for you to set show in your state if your want it to update when the prop updates.
class LoginComponent extends Component {
render() {
return (
<div className="login" style={{ display: (this.props.view ? 'block' : 'none') }}>
<h3>Login</h3><br/>
Username: <input type="text" ref="username"/><br/>
Password <input type="password" ref="password"/>
<button value="Login" >Login</button>
</div>
);
}
}
Related
What is v-if in react? I tried this but My div with loading class does not work when the loading data changes, so the div doesn't re-render itself.
codes is here:
{
loading &&
<div className="loading"></div>
}
I'm changing loading with a function, this function working with onclick event.
all of my code:
import React from "react";
import axios from "axios";
export class LoginPage extends React.Component{
render(){
let username = '',
password = '',
loading = false
function login(){
loading = true;
console.log(loading)
}
return (
<div className="App">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
crossOrigin="anonymous" referrerpolicy="no-referrer"/>
{
loading &&
<div className="loading"></div>
}
<div className="login">
<h1>Login/Register</h1>
<div>
<i className="fas fa-user"></i>
<input type="text" onChange={(e) => username = e.target.value} placeholder="Username" maxLength="15"/>
</div>
<div>
<i className="fas fa-lock"></i>
<input type="Password" placeholder="Password" onChange={(e) => password = e.target.value} maxLength="18"/>
</div>
<button onClick={() => login()}>Login/Register</button>
</div>
</div>
);
}
}
I'd suggest you read about React State, some things in this piece of code are wrong. But let's fix your problem.
First add this variable to the state and then change it with setState, to trigger a rerender:
export class LoginPage extends React.Component{
constructor(props) {
super(props);
this.state = {
loading: false
};
}
login(){
this.setState({ loading: true })
console.log(this.state.loading)
}
render(){
let username = '',
password = '',
// your return will stay the same
}
}
I have a relatively simple Bootstrap card layout in React with multiple cards, each of which has a toggle switch on it. However, whichever toggle switch is pressed it's always the handler function for the first card that is called (and hence the first toggle changes state). I can't understand why they aren't calling their own functions.
The structure I have is the card-deck has multiple card children, each of which has a toggle switch child, e.g. card deck -> card -> toggle
Card deck
class CardDeck extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{title: 'Cat 1'},
{title: 'Cat 2'},
{title: 'Cat 3'}
]
}
}
render() {
return (
<div class="card-deck">
{this.state.data.map((item, index) =>
<Card
key={index}
title={item.title}
index={index}
id={index}
/>
)}
</div>
);
}
}
Card
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
}
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked,
});
}
render() {
return (
<div class="card" key={this.props.index}>
<div class="card-body">
<h5 class="card-title">{this.props.title}</h5>
<p class="card-text">Text</p>
</div>
<div class="card-footer">
<Toggle checkStatus={this.state.checked} onChange={this.handleChange} key={this.props.index} />
</div>
</div>
);
}
}
Toggle
class Toggle extends React.Component{
render() {
return (
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitches" onChange={this.props.onChange} checked={this.props.checkStatus} />
<label class="custom-control-label" for="customSwitches">Label</label>
</div>
)
}
}
A simple workaround is to pass an id prop to toggle component because each checkbox control id should be unique but in your case, you are using the same id attribute value for all the three checkboxes so in other to differentiate the checkboxes I passed an id prop to toggle component and append to the id attribute value of each checkbox so as to make them unique.
Toggle Component
class Toggle extends React.Component {
render () {
console.log(this.props.id)
return (
<div className='custom-control custom-switch'>
<input
type='checkbox'
className='custom-control-input'
id={`customSwitches${this.props.id}`}
onChange={this.props.onChange}
checked={this.props.checkStatus}
/>
<label
className='custom-control-label'
htmlFor={`customSwitches${this.props.id}`}
>
Label
</label>
</div>
)
}
}
Card component
class Card extends React.Component {
constructor (props) {
super(props)
this.state = {
checked: false
}
this.handleChange = this.handleChange.bind(this)
}
handleChange () {
this.setState({
checked: !this.state.checked
})
}
render () {
return (
<div className='card' key={this.props.index}>
<div className='card-body'>
<h5 className='card-title'>{this.props.title}</h5>
<p className='card-text'>Text</p>
</div>
<div className='card-footer'>
<Toggle
checkStatus={this.state.checked}
onChange={this.handleChange}
key={this.props.index}
id={this.props.index}
/>
</div>
</div>
)
}
}
In the code below when the checkbox is checked in AddressWrapper the Ship To input in the AddressForm should be disabled. I can not figure out why AddressWrapper cloneElement is not passing it's state to the child. I have checked out many links about this issue and as far as I can tell this should work. This is the closest How to pass props to {this.props.children} to this problem but it is using a callback from the child to the parent and I need a change in parent state to update the child. I could use a publish/subscribe to do it but I'm trying to do it the 'React' way.
class AddressForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: "Joyce",
disableInputs: props.billToSameAsShipTo
};
this.handleBillToSameAsShipToChanged = this.handleBillToSameAsShipToChanged.bind(
this
);
}
handleBillToSameAsShipToChanged() {
this.setState({ billToSameAsShipTo: !this.state.billToSameAsShipTo });
}
handleFirstNameChanged(ev) {
this.setState({ firstName: ev.target.value });
}
render() {
return (
<form>
<div className="form-row">
<div className="col-6">
<input
type="text"
className="form-control"
placeholder="First name"
disabled={this.state.disableInputs}
value={this.state.firstName}
onChange={this.handleFirstNameChanged.bind(this)}
/>
</div>
</div>
</form>
);
}
}
class AddressFormWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
billToSameAsShipTo: true
};
this.handlebillToSameAsShipToChanged = this.handlebillToSameAsShipToChanged.bind(
this
);
}
handlebillToSameAsShipToChanged() {
this.setState({ billToSameAsShipTo: !this.state.billToSameAsShipTo });
}
render() {
const billToSameAsShipTo = () => {
if (this.props.showSameAsShipTo === true) {
return (
<span style={{ fontSize: "10pt", marginLeft: "20px" }}>
<input
type="checkbox"
checked={this.state.billToSameAsShipTo}
onChange={this.handlebillToSameAsShipToChanged}
/>
<span>Same as Ship To</span>
</span>
);
}
};
const childWithProp = React.Children.map(this.props.children, child => {
return React.cloneElement(child, { ...this.state });
});
return (
<span className="col-6">
<h3>
{this.props.title}
{billToSameAsShipTo()}
</h3>
<span>{childWithProp}</span>
</span>
);
}
}
const Checkout = () => {
return (
<div>
<br />
<br />
<div className="row">
<AddressFormWrapper title="Ship To" showSameAsShipTo={false}>
<span className="col-6">
<AddressForm />
</span>
</AddressFormWrapper>
<AddressFormWrapper title="Bill To" showSameAsShipTo={true}>
<span className="col-6">
<AddressForm />
</span>
</AddressFormWrapper>
</div>
</div>
);
};
In AddressFormWrapper you map over the children and passing props with cloneElement().
As per the DOCS:
Invokes a function on every immediate child contained within children...
But take a good look who are those (immediate) children of AddressFormWrapper:
<AddressFormWrapper title="Bill To" showSameAsShipTo={true}>
<span className="col-6">
<AddressForm />
</span>
</AddressFormWrapper>
In this case its the span element and not AddressForm.
If you render it like this it will work as expected:
<AddressFormWrapper title="Bill To" showSameAsShipTo={true}>
<AddressForm />
</AddressFormWrapper>
Another thing to watch out from, in AddressForm you are setting the state:
disableInputs: props.billToSameAsShipTo
This is inside the constructor and it will only run once. So it will get the initial value but won't get changed.
Either update it in componentDidUpdate or better just use the props directly:
disabled={this.props.billToSameAsShipTo}
Here is a running example:
class AddressForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: "Joyce",
disableInputs: props.billToSameAsShipTo
};
this.handleBillToSameAsShipToChanged = this.handleBillToSameAsShipToChanged.bind(
this
);
}
handleBillToSameAsShipToChanged() {
this.setState({ billToSameAsShipTo: !this.state.billToSameAsShipTo });
}
handleFirstNameChanged(ev) {
this.setState({ firstName: ev.target.value });
}
billToSameAsShipTo() {
if (this.props.showSameAsShipTo === true) {
return (
<span style={{ fontSize: "10pt" }}>
<input
type="checkbox"
checked={this.state.billToSameAsShipTo}
onChange={this.handleBillToSameAsShipToChanged}
/> <span>Same as Ship To</span>
</span>
);
}
}
render() {
return (
<form>
<div className="form-row">
<div className="col-6">
<input
type="text"
className="form-control"
placeholder="First name"
disabled={this.props.billToSameAsShipTo}
value={this.state.firstName}
onChange={this.handleFirstNameChanged.bind(this)}
/>
</div>
</div>
</form>
);
}
}
class AddressFormWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
billToSameAsShipTo: true
};
this.handlebillToSameAsShipToChanged = this.handlebillToSameAsShipToChanged.bind(
this
);
}
handlebillToSameAsShipToChanged() {
this.setState({ billToSameAsShipTo: !this.state.billToSameAsShipTo });
}
render() {
const billToSameAsShipTo = () => {
if (this.props.showSameAsShipTo === true) {
return (
<span style={{ fontSize: "10pt", marginLeft: "20px" }}>
<input
type="checkbox"
checked={this.state.billToSameAsShipTo}
onChange={this.handlebillToSameAsShipToChanged}
/> <span>Same as Ship To</span>
</span>
);
}
};
const childWithProp = React.Children.map(this.props.children, child => {
return React.cloneElement(child, { ...this.state });
});
return (
<span className="col-6">
<h3>
{this.props.title}
{billToSameAsShipTo()}
</h3>
<span>{childWithProp}</span>
</span>
);
}
}
const Checkout = () => {
return (
<div>
<br />
<br />
<div className="row">
<AddressFormWrapper title="Ship To" showSameAsShipTo={false}>
<span className="col-6">
<AddressForm />
</span>
</AddressFormWrapper>
<AddressFormWrapper title="Bill To" showSameAsShipTo={true}>
<AddressForm />
</AddressFormWrapper>
</div>
</div>
);
};
ReactDOM.render(<Checkout />, document.querySelector("#app"));
<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="app"/>
I'm working in a form with React. My idea is to create a reusable Form component that gets the state from a Page component as props, and will hold the logic for updating its own state with children data, send it to parent Page component.
The Page component is this:
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input id="text1" data={this.state.data.text1} />
<Input id="text2" data={this.state.data.text2} />
</Form>
</div>
);
}
}
This is the Form component:
class Form extends Component {
constructor(props) {
super(props);
this.state = this.props.data;
}
render() {
return (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{this.state.text1}</div>
<div>{this.state.text2}</div>
</div>
{this.props.children}
</div>
);
}
}
And this the Input component:
class Input extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component</div>
<input id={this.props.id} type="text" value={this.props.data} />
</div>
);
}
}
So Input should update Form state, and Form should update Page state. I know how to do it passing a callback when the Input is written Inside Form component, but I cant figure out how to do it when it is written inside Page component, like in this case.
I have a Sandbox for those interested: https://codesandbox.io/s/qx6kqypo09
class Input extends Component {
constructor(props) {
super(props);
}
handleChange(e) {
let data = this.props.this.state.data;
data.text1 = e.target.value;
this.props.this.setState({ data: data });
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component {this.props.id}</div>
<input
id={this.props.id}
type="text"
value={this.props.data}
onChange={e => this.handleChange(e)}
/>
</div>
);
}
}
use your input component as specified and your page component as mentioned below-
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input id="text1" this={this} data={this.state.data.text1} />
<Input id="text2" data={this.state.data.text2} />
</Form>
</div>
);
}
}
I think this will help you
Thanks
As #dashton said, I am holding the same state in different components, and that's not correct. I will look for a different approach instead using only Form component state, and sharing logic via composition. I will open a new question for this.
without using some kind of state management, you would need to create a method that handles the state change in the parent component that you would then pass down to your child component a a prop.
Once you call that method in the child component it will update the state of the parent component.
This is one way of doing what you want to achieve: passing a callback handler for onChange. But, when your app starts to get bigger things can be ugly :) If you are thinking about creating a complex reusable Form component maybe you can examine the present node packages.
An alternative to this method, if you need a simple one, you can study React Context a little bit. It can help you maybe. Other than that Redux or other global state management libraries can do this also.
class Page extends React.Component {
state = {
data: {
text1: "Initial text1",
text2: "Initial text2",
},
};
handleChange = ( e ) => {
const { name, value } = e.target;
this.setState( prevState => ( {
data: { ...prevState.data, [ name ]: value },
} ) );
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form data={this.state.data}>
<Input name="text1" data={this.state.data.text1} onChange={this.handleChange} />
<Input name="text2" data={this.state.data.text2} onChange={this.handleChange} />
</Form>
</div>
);
}
}
const Form = props => (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{props.data.text1}</div>
<div>{props.data.text2}</div>
</div>
{props.children}
</div>
);
const Input = props => (
<div className="Child" id={props.id}>
<div>Input component {props.id}</div>
<input name={props.name} type="text" value={props.data} onChange={props.onChange} />
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<Page />, rootElement);
.Page {
border: 10px solid blue;
}
.Parent {
border: 10px solid turquoise;
}
.Child {
border: 3px solid tomato;
}
.DataPreview {
border: 3px solid lightgray;
}
<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="root"></div>
As other people have said, you are holding the same state in different components, which obviously isn't correct.
However, to answer your requirement regarding decoupling child components from the form, you could make your form handle state changes from the inputs by using a render prop which would pass a callback to the inputs, see code and link.
https://codesandbox.io/s/4zyvjm0q64
import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Input extends Component {
constructor(props) {
super(props);
}
handleChange(id, value) {
this.props.onChange(id, value);
}
render() {
return (
<div className="Child" id={this.props.id}>
<div>Input component {this.props.id}</div>
<input
id={this.props.id}
type="text"
value={this.props.data}
onChange={e => this.handleChange(e)}
/>
</div>
);
}
}
class Form extends Component {
constructor(props) {
super(props);
this.state = this.props.data;
}
handleChange = (id, value) => {
this.setState({ [id]: value });
};
render() {
return (
<div className="Parent">
<div>Form component</div>
<div className="DataPreview">
Data preview in Form component
<div>{this.state.text1}</div>
<div>{this.state.text2}</div>
</div>
{this.props.render(this.handleChange)}
</div>
);
}
}
class Page extends Component {
constructor(props) {
super(props);
this.state = {
data: {
text1: "Initial text1",
text2: "Initial text2"
}
};
}
render() {
return (
<div className="Page">
<div className="DataPreview">
Data preview in Page component
<div>{this.state.data.text1}</div>
<div>{this.state.data.text2}</div>
</div>
<Form
data={this.state.data}
render={(handler) => {
return (
<div>
<Input id="text1" onChange={e => handler("text1", e.target.value)} />
<Input id="text2" onChange={e => handler("text2", e.target.value)} />
</div>
);
}}
/>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Page />, rootElement);
I have a simple component that displays data onClick event on a button. Here is my component:
import React, { Component } from 'react';
import './cardCheck.css';
class CardCheck extends Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = bool => {
this.setState({
showMessage: bool
});
};
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage.bind(null, true)} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage.bind(null, false)}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
export default CardCheck;
The code works, but I have this error in my console:
JSX props should not use .bind()
I read about it and changed my function to arrow ones like this:
import React, { Component } from 'react';
import './cardCheck.css';
class CardCheck extends Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = bool => () => {
this.setState({
showMessage: bool
});
};
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage()} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage()}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
export default CardCheck;
The error is gone, but my code does not work now. What is the correct way to do this with arrow functions and still make it work?
Either binding or using arrow function is not suggested since those functions will be recreated in every render. This is why you see those warnings. Instead of binding or invoking with an arrow function use it with reference and change your function a little bit.
_showMessage = () =>
this.setState( prevState => ( {
showMessage: !prevState.showMessage,
}) );
Instead of using a boolean, we are changing showMessage value by using its previous value. Here, we are using setState with a function to use previous state since setState itself is asynchronous.
And in your element you will use this function with its reference.
<input type="submit" value="Check" onClick={this._showMessage} />
Working example.
class CardCheck extends React.Component {
constructor(props) {
super(props);
this.state = { showMessage: false };
}
_showMessage = () =>
this.setState( prevState => ( {
showMessage: !prevState.showMessage,
}) );
render() {
return (
<div>
<div className="newsletter-container">
<h1>Enter the ID of your card:</h1>
<div className="center">
<input type="number" />
<input type="submit" value="Check" onClick={this._showMessage} />
</div>
<div className="results" />
{this.state.showMessage && (
<div>
hello world!
<button onClick={this._showMessage}>hide</button>
</div>
)}
</div>
<h1>Offers:</h1>
</div>
);
}
}
ReactDOM.render(
<CardCheck />,
document.getElementById("root")
);
<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="root"></div>
<input type="submit" value="Check" onClick={this._showMessage()} />
You are invoking the _showMessage function by having the () in the onClick handler. You just want to pass the reference to the function, i.e. without ()
<input type="submit" value="Check" onClick={this._showMessage} />