Passing state from child class to parent - javascript

I know that this is probably the most asked question about React, but none of the answers helped me.
I have 2 classes:
Child
class Preview extends Component {
constructor(...args) {
super(...args);
this.state = {
isCommentOpen: false
};
this.handleComment = ::this.handleComment;
render() {
return(
button type="button" onClick={this.handleComment}>Comment</button>
)}
handleComment(){
this.setState({isCommentOpen: !this.state.isCommentOpen});
}
export default Preview;
Parent
class Profile extends Component {
render(){
return(
<div>
<_.Preview />
//the place where I want to add validation from the component above
{this.state.isCommentOpen ? <span>Cool</span> : null}
</div>
}

You should not mutate or directly assign this.props as shown in the other answer:
this.props.isCommentOpen = !this.props.isCommentOpen // <-- DON'T DO THIS! 🎃
Instead, you should have a callback function to let the Parent component update the child component:
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
isCommentOpen: false;
}
this.handleComment = this.handleComment.bind(this); // <-- important!
}
handleComment() {
this.setState({ isCommentOpen: !this.state.isCommentOpen });
}
render() {
return (
<div>
<Preview handleComment={this.handleComment} />
{ this.state.isCommentOpen ? <span>Cool</span> : null }
</div>
)
}
}
export default Profile
The child component then only needs to call this.props.handleComment:
// Child Component:
class Preview extends Component {
render() {
return(
<button type="button" onClick={this.props.handleComment}>Comment</button>
}
}
export default Preview;

Related

how to pass state values as props to child component

I am trying to pass some constant values which is stored in state of parent component to child component and would like to pass down in tree.
is it right to store the constant values in state of App.tsx or any other suggestion
how can i access for example GrTag or sTag from App.tsx to Subchild component.
App.tsx
class App extends Component {
constructor(props) {
super(props);
this.state = {
sTag : "00D",
pTag : "010",
adTag : "020",
dbTag : "030",
GrTag : "040",
serTag : "00E",
modTag : "060",
iTag: "018"
};
}
render() {
return(
<div >
<Child {...this.state}/> //is this right way to pass
</div>
);
}
}
Child.tsx
class Child extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
<Subchild /> //want to pass the state values from App.tsx
}
</div>
);
};
}
Subchild.tsx
class Subchild extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
// want to print sTag value here
}
</div>
);
};
}
The way you are spreading the state {...this.state} will pass all the state values as props to the child components . If you need all the state values in your Child component as props then what you are doing is fine .
But if you just need the stag from the App inside the subChild then you can do
<Child {...this.state}/>
In your Child.tsx
<Subchild {...this.props} />
To solve your problem, pass the props from the child to the sub child. Like this;
class Child extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
<Subchild {...this.props}/> //want to pass the state values from App.tsx
}
</div>
);
};
}
But mind you. This is not a good way to pass data to components.
If you have data that can be shared amongst many components in your app, consider using REACT REDUX or MOBX. I personally recommmend using Redux.
App.tsx
class App extends Component {
constructor(props) {
super(props);
this.state = {
sTag : "00D",
pTag : "010",
adTag : "020",
dbTag : "030",
GrTag : "040",
serTag : "00E",
modTag : "060",
iTag: "018"
};
}
render() {
return(
const data = this.state;
<div >
<Child dataToClid = {data}/> //is this right way to pass
</div>
);
}
}
Child.tsx
class Child extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.dataToClid
}
}
render(){
const data = this.state;
return(
<div>
{
<Subchild dataToSubClid = {data}/> //want to pass the state values from App.tsx
}
</div>
);
};
}
SubChild.tsx
class Subchild extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.dataToSubClid
}
}
render(){
const {GrTag, sTag} = this.state;
return(
<div>
<p>{GrTag}</p>
<p>{sTag}</p>
</div>
);
};
}
you can do this way or you can use Context API for pass data from parent to child

ReactJS - change class of component from another component?

Very new to React, and coming from a jQuery background, the first thing I want to be able to do is toggle classes.
I understand how I can toggle a class within the same react component like this:
class ButtonParent extends React.Component {
constructor(props) {
super(props)
this.state = {
condition: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
condition: !this.state.condition
})
}
render() {
return (
<ButtonChild
className={ this.state.condition ? "button toggled" : "button" }
toggleClassName={ this.handleClick }
>
Click me if you dare!
</ButtonChild>
)
}
}
class ButtonChild extends React.Component {
render() {
return (
<div
className={ this.props.className }
onClick={ this.props.toggleClassName }
>
{ this.props.children }
</div>
)
}
}
ReactDOM.render(<ButtonParent />, document.getElementById('app'))
But what if I have a a separate component that I want to use in order to toggle the class of the component? Is there no easy way to do this in React?
Thanks!
Just create an ButtonChild.js file near your ButtonParent.js file and export your component
export default class ButtonChild extends React.Component {
render() {
return (
<div
className={ this.props.className }
onClick={ this.props.toggleClassName }
>
{ this.props.children }
</div>
)
}
}
Import it in you ButtonParent.js file like this
import ButtonChild from './ButtonParent.js'

React JS - Passing functions for child components

I have an App component and a function 'modalToggled' inside its.
I want to pass the function to multiple child components until I get to the last one, the 'interiores' component.
Like this:
<App> -> <Coluna1> -> <MenuPrincipal> -> <Portfolio> -> <PortfolioMenu> -> <interiores>
App Component, the parent of all components:
import React, { Component } from 'react';
import Coluna1 from './Coluna1'
class App extends Component {
constructor(props) {
super(props)
this.state = {
modalOn: false
}
this.modalToggled = this.modalToggled.bind(this)
}
modalToggled = (on) => {
this.setState({modalOn: on});
}
render() {
return (
<div>
<Coluna1 onModalToggle={this.modalToggled}/>
</div>
)
}
}
export default App;
This is the 'Coluna1' the first child component. I did the same thing in the another ones: 'MenuPrincipal', 'Portfolio', 'PortfolioMenu'
class Coluna1 extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<Header />
<MenuPrincipal onModalToggle={this.props.modalToggled} />
</div>
)
}
}
export default Coluna1
Therefore here is the last component interiores, when I click on the button there appears an error message:
TypeError: _this.props.onModalToggle is not a function
import React, { Component } from 'react'
import Modal from 'react-responsive-modal';
class Interiores extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
onOpenModal = () => {
this.setState({ open: true });
this.props.onModalToggle(true);
};
onCloseModal = () => {
this.setState({ open: false });
this.props.onModalToggle(false);
};
render() {
const { open } = this.state;
return (
<div>
<button onClick={this.onOpenModal}>Open modal</button>
<Modal open={open} onClose={this.onCloseModal} center></Modal>
</div>
)
}
}
export default Interiores;
Does anybody know how to solve it? Thank you
It happens, because in App class you pass prop with name onModalToggle:
<Coluna1 onModalToggle={this.modalToggled}/>
But in Coluna1 you receive this props with wrong name, modalToggled:
<MenuPrincipal onModalToggle={this.props.modalToggled} />
Just make the names of props equal. In Coluna1 and other intermediate components pass and receive this props as onModalToggle:
<MenuPrincipal onModalToggle={this.props.onModalToggle} />
This is the problem
modalToggled = (on) => {
this.setState({modalOn: on});
}
Since this is a class function it needs to be defined like
modalToggled(on) {
this.setState({modalOn: on});
}

ReactJS calling functions from child component [duplicate]

I have a parent and child compoents and I want to call a parent method in the child component like this:
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click() {
Parent.someMethod();
}
render() {
<div>Hello Child onClick={this.click}</>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<div>Hello Parent</>
}
}
This returns an error message:
Uncaught TypeError: _Parent2.default.someMethod is not a function
How can this parent method be called in the child component?
Try this. Passing the function down as props to the child component.
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click = () => {
this.props.parentMethod();
}
render() {
<div onClick={this.click}>Hello Child</div>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}
You can try doing something like calling the function of parent by passing the state of your parent to the child and then call using the props in child class.
class FlatListItem extends Component{
constructor(props){
super(props)
}
render(){
return(
<TouchableOpacity style={styles.button}
onPress=
{(item)=>this.props.parentFlatlist.delete(item)}></TouchableOpacity>
</Swipeout>
)
}}
And now consider you have a parent class RandomList:
class RandomList extends Component{
static navigationOptions = ({navigation}) =>{
return{
headerTitle: 'Random List'
}
};
state = {
lists : [],
refreshing : false
}
constructor(props){
super(props)
}
delete= (item) =>{
//delete your item
console.log(item)
}
render(){
return(
<BackgroundImageComponent>
<FlatList
keyExtractor={item => item}
data = {this.state.lists}
renderItem = {({item,index}) => (
<FlatListItem onPress={()=>this.seeTheList(item)} item1={item} parentFlatList={this} index={index}>
</FlatListItem>
)}
/>
</ScrollView>
</BackgroundImageComponent>
)
}}export default RandomList
See here, I am passing parentFlatlist={this} and then would be using the same instance later in the child class.
The main idea is to focus upon the way I am able to render the delete function and not to focus upon the code. Forgive me if the code is misplaced or broken.

Can I modify a parent state of a component in ReactJs?

Let's say I'm having the following component:
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.state = {abc: 'xyz'};
}
render() {
return (
<div>
<Thumb src={img1}/>
<Thumb src={img2}/>
</div>);
}
Inside the component, there's an inner component called Thumb that goes like there:
class Thumb extends React.Component {
constructor(props) {
super(props);
this.state = { src: props.src };
}
render() {
return (
<div>
<img src={this.state.src}></img>
</div>
);
}
}
Question: Can I modify the state of LeftPanel Component inside Thumb? If yes, how?
create a method in Left panel to handle the event. Then pass the method to the child component.
Now if you want to pass data to the parent I would recommend a library like flux or redux. since redux has a global state it is accessible to all components. When you modify the global state to whole application is rerendered with the new state. The new state is visible by all components.
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.modifyLeftpanel = this.modifyLeftpanel.bind(this);
this.state = {abc: 'xyz'};
}
modifyLeftpanel(newvar){
//Do something with newvar
}
render() {
return (
<div>
<Thumb src={img1} modifyLeftPanel={this.modifyLeftpanel} />
<Thumb src={img2} modifyLeftPanel={this.modifyLeftpanel} />
</div>);
}
here is the thumb
class Thumb extends React.Component {
constructor(props) {
super(props);
this.state = { src: props.src };
this.doSomething = this.doSomething.bind(this);
}
doSomething(){
this.props.modifyLeftpanel(10);
}
render() {
return (
<div>
<img src={this.state.src}></img>
<button onClick={this.doSomething}>Modify Parent</button>
</div>
);
}

Categories

Resources