The following code example contains 2 components: Component1 logs prevState with componentDidUpdate method, Component2 is removed on a button click to show the use of componentWillUnmount.
const { useState } = React;
class Component1 extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'John',
};
}
componentDidUpdate(prevProps, prevState) {
console.log(prevState);
}
render() {
return (
<div>
<div>The name is {this.state.name}</div>
<label htmlFor="prevstate">Type here to see prevState in console: </label>
<input
id="prevstate"
onChange={(e) => {
this.setState({ name: e.target.value });
}}
/>
</div>
);
}
}
class Component2 extends React.Component {
componentDidMount() {
console.log('Mount');
}
componentWillUnmount() {
console.log('Unmount');
}
render() {
return (
<div>
<div>Click the button to remove the element</div>
</div>
);
}
}
const App = () => {
const [showComponent, setShowComponent] = useState(true);
return (
<div>
<Component1 />
{showComponent ? <Component2 /> : null}
<button
onClick={() => {
setShowComponent(false);
}}
>
Remove
</button>
</div>
);
};
// Render it
ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Now I find that these 2 components interfere with each other: clicking the button also logs the prevState in the first component. What I thought would happen was that the componentDidUpdate method would only monitor the update of Component1, but seems it monitors the button which is outside of both components, why does this happen?
When the App is rendered, its children are rendered as well. You might try making Component1 a React.PureComponent or defining shouldComponentUpdate if you want to reduce the rerendering.
Related
I have the following example where the toggleComponent.js is working perfectly.
The problem here is that I don't want to render the <ContentComponent/> inside the toggle, rather I want the opposite, I want to toggle the <ContentComponent/> that will be called in another component depending on the state of the toggle.
So the <ContentComponent/> is outside the toggleComponent.js, but they are linked together. So I can display it externally using the toggle.
An image to give you an idea:
Link to funtional code:
https://stackblitz.com/edit/react-fwn3rn?file=src/App.js
import React, { Component } from "react";
import ToggleComponent from "./toggleComponent";
import ContentComponent from "./content";
export default class App extends React.Component {
render() {
return (
<div>
<ToggleComponent
render={({ isShowBody, checkbox }) => (
<div>
{isShowBody && <h1>test</h1>}
<button onClick={checkbox}>Show</button>
</div>
)}
/>
<ToggleComponent
render={({ isShowBody, checkbox }) => (
<div>
{isShowBody && (
<h1>
<ContentComponent />
</h1>
)}
<button onClick={checkbox}>Show</button>
</div>
)}
/>
</div>
);
}
}
Bit tweaked your source.
Modified ToggleComponent
import React from "react";
export default class ToggleComponent extends React.Component {
constructor() {
super();
this.state = {
checked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
this.setState({ checked: !this.state.checked });
this.props.toggled(!this.state.checked);
};
checkbox = () => {
return (
<div>
<label>Toggle</label>
<span className="switch switch-sm">
<label>
<input type="checkbox" name="select" onClick={this.handleClick} />
<span />
</label>
</span>
</div>
);
};
render() {
return this.checkbox();
}
}
Added OtherComponent with ContentComponent inside.
import React, { Component } from "react";
import ContentComponent from "./content";
export default class OtherComponent extends React.Component {
render() {
return <div>{this.props.show ? <ContentComponent /> : null}</div>;
}
}
Separated as per your requirement.
Modified App
import React, { Component, PropTypes } from "react";
import ToggleComponent from "./toggleComponent";
import OtherComponent from "./otherComponent";
export default class App extends React.Component {
constructor() {
super();
this.toggled = this.toggled.bind(this);
this.state = { show: false };
}
toggled(value) {
this.setState({ show: value });
}
render() {
return (
<div>
<ToggleComponent toggled={this.toggled} />
<OtherComponent show={this.state.show} />
</div>
);
}
}
Working demo at StackBlitz.
If you want to share states across components a good way to do that is to use callbacks and states. I will use below some functional components but the same principle can be applied with class based components and their setState function.
You can see this example running here, I've tried to reproduce a bit what you showed in your question.
import React, { useState, useEffect, useCallback } from "react";
import "./style.css";
const ToggleComponent = props => {
const { label: labelText, checked, onClick } = props;
return (
<label>
<input type="checkbox" checked={checked} onClick={onClick} />
{labelText}
</label>
);
};
const ContentComponent = props => {
const { label, children, render: renderFromProps, onChange } = props;
const [checked, setChecked] = useState(false);
const defaultRender = () => null;
const render = renderFromProps || children || defaultRender;
return (
<div>
<ToggleComponent
label={label}
checked={checked}
onClick={() => {
setChecked(previousChecked => !previousChecked);
}}
/>
{render(checked)}
</div>
);
};
const Holder = () => {
return (
<div>
<ContentComponent label="First">
{checked => (
<h1>First content ({checked ? "checked" : "unchecked"})</h1>
)}
</ContentComponent>
<ContentComponent
label="Second"
render={checked => (checked ? <h1>Second content</h1> : null)}
/>
</div>
);
};
PS: A good rule of thumb concerning state management is to try to avoid bi-directional state handling. For instance here in my example I don't use an internal state in ToggleComponent because it would require to update it if given checked property has changed. If you want to have this kind of shared state changes then you need to use useEffect on functional component.
const ContentComponent = props => {
const { checked: checkedFromProps, label, children, render: renderFromProps, onChange } = props;
const [checked, setChecked] = useState(checkedFromProps || false);
const defaultRender = () => null;
const render = renderFromProps || children || defaultRender;
// onChange callback
useEffect(() => {
if (onChange) {
onChange(checked);
}
}, [ checked, onChange ]);
// update from props
useEffect(() => {
setChecked(checkedFromProps);
}, [ checkedFromProps, setChecked ]);
return (
<div>
<ToggleComponent
label={label}
checked={checked}
onClick={() => {
setChecked(previousChecked => !previousChecked);
}}
/>
{render(checked)}
</div>
);
};
const Other = () => {
const [ checked, setChecked ] = useState(true);
return (
<div>
{ checked ? "Checked" : "Unchecked" }
<ContentComponent checked={checked} onChange={setChecked} />
</div>
);
};
I have the following Code using https://ant.design/components/checkbox/, and Trying to uncheck when a checkbox has been checked.
I don't want to check all if button is click, just Uncheck all or the one checkbox selected.
constructor(props) {
super(props);
this.state = {
checked: true,
}
this.onChange = this.onChange.bind(this);
}
onChange(value) {
this.props.onChangeSession(value)
}
onChangeBox = e => {
this.setState({
checked: e.target.checked,
});
};
unChecked = () => {
this.props.onChangeSession([])
this.setState({
checked: false
});
};
render () {
const {
data,
} = this.props
return (
<div>
<Button type="primary" size="small" onClick={this.unChecked}>
Uncheck
</Button>
<Checkbox.Group
style={{ width: '100%' }}
onChange={this.onChange}>
<div>
<div className="filter-subhead">Track</div>
{data.map(i =>
<div className="filter-item">
<Checkbox
checked={this.state.checked}
onChange={this.onChangeBox}
value={i}>{i}</Checkbox>
</div>
)}
</div>
</Checkbox.Group>
</div>
)
}
Any help will be appreciate!
Working Link
The toggle on the checkbox wasn't working due to Checkbox.Group, you can simply use Checkbox
Regarding Checkbox State:
You can't have a single state for all the checkboxes, so you will need to have an array of bool which will serve as the state for each checkbox item.
In the example, I have initialized checkbox state on componentDidMount and it creates an array ([false,false,false,...]) and the exact same thing is used for resetting on Uncheck. (Possibility of refactoring in my code)
User assigned state will decide whether to check the checkbox or not.
import React from "react";
import ReactDOM from "react-dom";
import { Button, Checkbox } from "antd";
import "antd/dist/antd.css";
import "./index.css";
let data = [3423, 3231, 334234, 55345, 65446, 45237];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
checkboxArray: []
};
// this.onChange = this.onChange.bind(this);
}
componentDidMount() {
let createEmptyArray = new Array(data.length).fill(false);
this.setState({ checkboxArray: createEmptyArray });
}
onChange(e) {
console.log(e.target);
}
onChangeBox = (e, i) => {
let checkBoxCurrentState = this.state.checkboxArray;
checkBoxCurrentState[i] = !checkBoxCurrentState[i];
this.setState({
checkboxArray: checkBoxCurrentState
});
};
unChecked = e => {
let resetArray = new Array(data.length).fill(false);
this.setState({
checkboxArray: resetArray
});
};
render() {
const { data } = this.props;
return (
<div>
<Button type="primary" size="small" onClick={this.unChecked}>
Uncheck
</Button>
<div>
<div className="filter-subhead">Track</div>
{data.map((i, index) => (
<div className="filter-item">
<Checkbox
checked={this.state.checkboxArray[index] ? true : false}
onChange={e => this.onChangeBox(e, index)}
value={index}
>
{JSON.stringify(this.state.checkboxArray[index])}
</Checkbox>
</div>
))}
</div>
{JSON.stringify(this.state.checkboxArray)}
</div>
);
}
}
ReactDOM.render(<App data={data} />, document.getElementById("root"));
Simple copy and paste the above code and add props where required.
And if you want to user Checkbox.Group, will need to update the onChange method of CheckBox.Group
let data = ['Apple', 'Pancakes', 'Butter', 'Tea', 'Coffee'];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
checkboxArray: []
};
// this.onChange = this.onChange.bind(this);
}
componentDidMount() {
let createEmptyArray = new Array(this.props.data.length).fill(false);
this.setState({ checkboxArray: createEmptyArray });
}
onChangeBox = (e, i) => {
let checkBoxCurrentState = this.state.checkboxArray;
checkBoxCurrentState[i] = !checkBoxCurrentState[i];
this.setState({
checkboxArray: checkBoxCurrentState
});
};
unChecked = () => {
let resetArray = new Array(data.length).fill(false);
this.setState({
checkboxArray: resetArray
});
};
render() {
const { data } = this.props;
return (
<div>
<button onClick={this.unChecked}>Clear All</button>
{this.props.data.map((single, index) => (
<div>
<input
type="checkbox"
id={index}
name="scales"
checked={this.state.checkboxArray[index]}
onChange={e => this.onChangeBox(e, index)}
/>
<label for={index}>{single}</label>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App data={data} />, 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>
If you're going to use a map to dynamically generate the checkboxes, using state to keep track of checked value will be tricky. You should not do this.
What you should do is not include the checked prop at all in the component.
<Checkbox
onChange={this.onChangeBox}
value={i}>{i}
</Checkbox>
The checkbox should still check even if you do not include the checked prop. It's a little strange, I know.
Instead just pass the value into the onChangeBox function and handle all your logic there and set a state value on change.
I just tested it out and it works.
I need to know the height of a React Component inside another React component. I am aware that the height of an element can be reached by calling this.cmref.current.clientHeight. I'm looking for something like this:
child component:
const Comp = () =>{
return(
<div>some other stuff here</div>
)
}
export default Comp
parent component:
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidSomething(){
const height = this.compref.current.clientHeight;
//which will be undefined
}
render(){
return(
<div>
<Comp ref={this.compref} />
</div>
)
}
}
Is this possible? Thanks in advance.
You'll need to actually ref the div of the child component in order to get the element you want instead of the child component itself. To do this you could pass a function to the child that the child then passes to the div. Working example below:
const Comp = (props) =>{
return(
<div ref={props.onRef}>some other stuff here</div>
)
}
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidMount(){
const height = this.compref.current.clientHeight;
//which will be undefined --- No more!
console.log('height: ', height);
}
onCompRef = (ref) => {
this.compref.current = ref;
}
render(){
return(
<div>
<Comp onRef={this.onCompRef} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='root' style='width: 100%; height: 100%'>
</div>
const Comp = React.forwardRef((props, ref) => (
<div ref={ref}> some other stuff here </div>
));
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidMount(){
const height = this.compref.clientHeight;
console.log("hieght", height);
}
render(){
return(
<div>
<Comp ref={(el) => this.compref = el} />
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
Could you try this way. Hope it helps. Please refer forward refs https://reactjs.org/docs/forwarding-refs.html
Passing a dynamic property of onClick= do something by the use of ref gives me back: TypeError: _this.listReference is null listReference is defined in one of my components that i will show below.
In Component #1
class Component1 extends Component {
constructor(props){
super(props)
this.listReference= null;
}
//Returns
<div>
<SomeComponent list={(ref) => this.listReference= ref} />
<Component2 onMarkerClick = {(index) => {
this.listReference.scrollTop = 48 * index
}}/>
In Component #2
render() {
const {classes, driversStore, onMarkerCLick} = this.props
...
{driversStore.sortedSelectedOrders.map((order , index) => {
return (
<Component3
onClick={ () => onMarkerClick(index)} />
In Component #3
render() {
const { onClick } = this.props;
return (
<div
onClick={onClick}>
I expect upon click to trigger the scroll functionality (as Stated in Component #1).
Thanks in advance!
Check this example. Hope it can help you!
const Component2 = (props) =>(
<button onClick={props.onClick}>click me</button>
);
const SomeCompo = (props) =>(
<div>SomeComponent</div>
);
class Component1 extends React.Component{
listReference = React.createRef();
render(){
return(
<div>
<SomeCompo list={this.listReference}>reference</SomeCompo>
<Component2 onClick={this.handleClick} />
</div>
);
}
handleClick = () => {
if(this.listReference){
this.listReference={scrollTop:100};
}
console.log(this.listReference)
}
}
ReactDOM.render(<Component1/>,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>
You should do the following in constructor,
this.listReference = React.createRef()
I'm trying to build simple todo application with new context API but I'm having a hard time trying to debug why my input value is undefined.
I don't quite understand how to execute a function provided by Provider and pass arguments to it.
here is my code:
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
const AppContext = React.createContext();
class AppProvider extends Component {
constructor(props) {
super(props);
this.state = {
todoList: [{ text: "first test element", isCompleted: false }]
};
}
addTodo = (e) => {
e.preventDefault();
console.log(e.target.value);
this.setState({
todoList: [
...this.state.todoList,
{ text: e.target.value, isCompleted: false }
]
});
};
render() {
const { todoList, uniqueId } = this.state;
return (
<AppContext.Provider
value={{ todoList, addTodo: this.addTodo }}
>
{this.props.children}
</AppContext.Provider>
);
}
}
const Consumer = AppContext.Consumer;
class App extends Component {
constructor(props) {
super(props);
this.state = { value: "" };
}
render() {
return <AppProvider>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">TodoList</h1>
</header>
<Consumer>
{state => <form onSubmit={state.addTodo}>
<input type="text" />
<button type="submit" onSubmit={state.addTodo}>
Add Todo
</button>
</form>}
</Consumer>
<Consumer>
{val => (
<ul>
{val.todoList.map((item, index) => (
<li key={index}>{item.text}</li>
))}
</ul>
)}
</Consumer>
</div>
</AppProvider>;
}
}
export default App;
Sorry if my questions is trivial but I've been trying to solve it for quite a bit and I can't find what's wrong.
You just had some issues with how your form was sending the value through. Also, you should try decouple your events and your state, as shown in the working example here.