How to change a property value with an onClick event in React - reactjs

Assume the following Component:
class App extends Component {
constructor(props){
super(props);
}
func1 = () => {
....
}
func2 = () => {
...
}
render() {
return (
<div>
<Component
activity={this.func1}
/>
</div>
);
}
}
How can I implement an onClick event from the inside the Component function so as the result in the main App would be:
<div>
<Component
activity={this.func2}
/>
</div>

Normal flow is as below
class App extends Component {
constructor(props){
super(props);
}
func1 = () => {
....
}
func2 = () => {
...
}
render() {
return (
<div>
<Component
activity={this.func1}
/>
</div>
);
}
}
<div>
<Component
activity={this.props.activity(arguments)}
/>
</div>
and doing this will have the activity prop call the func1 defined in the parent component..
Note:- ideally you should call a function as prop for events and not just normal attributes

Related

Handling Parent function call in Child in React

Is it possible to create a method in Parent class in React and then pass it on to the Child and use it there.
So basically I would create a button in my Parent class, pass the function on to the Child and when the Button is clicked, the child will know about it and Parent will not really care for it?
class App extends Component {
clickMade = () => {
//This should be left empty
};
render() {
return (
<div className="App">
<Button onClick={this.clickMade}>Click me </Button>
<Child clickMade={this.clickMade} />
</div>
);
}
}
export default App;
And the Child:
class Child extends Component {
constructor(props) {
super(props);
this.handleClick = this.props.clickMade.bind(this);
}
handleClick = () => {
console.log("Click in child");
}
render() {
return null;
}
}
export default Child;
And a sandbox for this: CodeSandbox
App.js
class App extends Component {
clickMade = () => {
this.childRef.handleClick();
};
render() {
return (
<div className="App">
<Button onClick={this.clickMade}>Click me </Button>
<Child
ref={ref => {
this.childRef = ref;
}}
/>
</div>
);
}
}

passing state of child component

So I have a component "itemSelection" and inside of it I map through an api response like this
<div className="row">
{this.state.items.map(i => <Item name={i.name} quantity={i.quantity} />)}
</div>
Here the state of "Item" component
constructor(props){
super(props);
this.state = {
visible: false,
selected: false,
}
}
How could I pass the state of "Item" component to "itemSelection" component?
Sending data back up to your parent component should be done by using props.
Fairly common question, see this post for the long answer.
As according to me, If I understood your question you want to call the state of the child component to the parent component.
//Child.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
export default withStyles(s)(Child);
//Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert()
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick.bind(this)}>Click</button>
</div>
);
}
}
Also, you can get the code reference from the link: https://github.com/kriasoft/react-starter-kit/issues/909
This a little tricky but Maybe, its help you solving your problem.
//Parent.js
class Parent extends Component {
component(props) {
super(props)
this.state = {
test: 'abc'
}
}
ParentFunction = (value) => {
this.state.test = value;
this.setState(this.state);
}
render() {
return (
<div>
<Child
test={this.state.test}
ParentFunction={this.ParentFunction}
/>
</div>
);
}
}
//Child.js
import s from './Child.css';
class Child extends Component {
component(props) {
super(props)
this.state = {
test: props.test
}
}
handleChange = () => {
this.state.test = event.target.value;
this.setState(this.state);
this.handleOnSave()
}
handleOnSave = () => {
this.props.ParentFunction(this.state.test);
}
render() {
return (
<div>
<input type="text" onChange={this.handleChange} />
</div>
);
}
}
export default withStyles(s)(Child);

Send a prop to a child component

I am trying to change one component of a child component when another child component makes some action.
I have a parent class here:
class Parent extends Component {
constructor(){
super();
this.state={visible:true};
}
handleClick = () => {
this.setState({ visible: !this.state.visible });
};
render() {
return (
<div>
<Child1 handleClick={this.handleClick} />
<Child2 visible={this.state.visible} />
</div>
);
}
}
class Child1 extends Component {
handleClick = () => {
console.log(this.props);
this.props.handleClick();
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
class Child2 extends Component {
render() {
return <div>//some codes</div>;
}
}
The function handleClick from the parent function works once.
Then it keeps giving me the error saying _this.props.handleClick is not a function. And there are no props from the second time.
Can anyone tell me what am I doing wrong?
I did this and it works :
render() {
return (
<div>
<Child1 handleClick={this.handleClick} />
{ this.state.visible && <Child2 />}
</div>
);
}
For reference : https://codesandbox.io/s/5zl8q7l744
Hope it helps.

How to setState in child component when child function called from parent component in ReactJS

I want to call child function from parent component so I found a question here
Call child method from parent
So I used this way to to called it (From 1st Answer and 2nd approach).
Now issue is how to set state in the child getAlert function
class Parent extends Component {
render() {
return (
<div>
<Child ref={instance => { this.child = instance; }} />
<button onClick={() => { this.child.getAlert(); }}>Click</button>
</div>
);
}
}
class Child extends Component {
constructor(){
super();
this.state = {message:""};
}
getAlert() {
alert('clicked');
//HERE I NEED TO SETSTATE
}
render() {
return (
{this.state.message!=""?(
<h1>{this.state.message}</h1>
):(
<h1>Hello</h1>
)}
);
}
}
In the getAlert function of child I need to setState but I couldn't able to do it. Please provide any solution
The problem seems to be that when calling setState inside the getAlert function of child, this.setState will come undefined. This happens because this inside your getAlert function doesn't refer to the context of the React Component and setState is defined for the Component. You can solve this by binding the getAlert function.
You can do it in two ways.
First: using .bind(this) in constructor
class Child extends Component {
constructor() {
super();
this.getAlert = this.getAlert.bind(this);
}
getAlert() {
alert('clicked');
//HERE I NEED TO SETSTATE
}
render() {
return (
<h1>Hello</h1>
);
}
}
Second: use Arrow function
getAlert = () => {
alert('clicked');
//HERE I NEED TO SETSTATE
}
Check this answer on Why do we need to bind React functions
Check the working snippet
class Parent extends React.Component {
render() {
return (
<div>
<Child ref={instance => { this.child = instance; }} />
<button onClick={() => { this.child.getAlert(); }}>Click</button>
</div>
);
}
}
class Child extends React.Component {
constructor(){
super();
this.state = {message:""};
}
getAlert = () => {
alert('clicked');
this.setState({message: "somemessage"});
}
render() {
return (
<div>{this.state.message!=""?(
<h1>{this.state.message}</h1>
):(
<h1>Hello</h1>
)}</div>
);
}
}
ReactDOM.render(<Parent/>, document.getElementById('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"/>
class Parent extends React.Component {
render() {
return (
<div>
<Child ref={instance => { this.child = instance; }} />
<button onClick={() => { this.child.getAlert(); }}>Click</button>
</div>
);
}
}
class Child extends React.Component {
constructor(){
super()
this.state = {
message: 'google'
}
this.getAlert = this.getAlert.bind(this)
}
getAlert() {
alert('clicked');
this.setState ({
message: 'yahoo'
}, () => {
console.log(this.state.message) //the state value will be printed
});
}
render() {
console.log(this.state.message)
return (
<h1>Hello {this.state.message}</h1>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
<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="container"></div>
you have bind the getAlert() method to scope of the class ie). 'this'. I have added an sample code..pls check

Trigger event when the state of child of another component changed in react

Let say I have two components called A and B.
B has a status which keeps changing and I would like to pass the status to A so that I can trigger event when certain condition is met.
How do I keep monitoring/getting state of child from another component in React?
Thanks!
When component on the same level:
class Parent extends React.Component {
constructor() {
super();
this.state = {
status: "B not clicked"
}
this.componentBchangeHandler = this.componentBchangeHandler.bind(this);
}
componentBchangeHandler(value) {
this.setState({ status: value })
}
render() {
return (
<div>
<ComponentA status={this.state.status} />
<ComponentB componentBchangeHandler={this.componentBchangeHandler} />
</div>
)
}
}
const ComponentA = (props) => <div>{props.status}</div>;
const ComponentB = (props) => <div onClick={() => props.componentBchangeHandler("some val")}>click me</div>;
https://codesandbox.io/s/k29mn21pov
And check out the documents I mentioned earlier.
If you're talking about a parent-child relationship, all you'd have to do is define a function that changes state on A and pass it as prop to B, like so:
class A extends Component {
constructor(props) {
super(props);
this.state = {
changed: false,
}
}
_statusChange = () => this.setState({ changed: !this.state.changed });
render() {
return(
<div>
<span>State on A: { this.state.changed.toString() }</span>
<B changeHandler={this._statusChange} />
</div>
)
}
}
class B extends Component {
render() {
return(
<div>
<button onClick={this.props.changeHandler}>Click me</button>
</div>
)
}
}
const App = () => (
<A />
);
If they should be on the same level, by convention, you should define a third component, wrap A and B in it, again passing state as props between them.

Resources