React passing props to child and back to parent - reactjs

My current structure is like this:
state={
activetab=1,
activetab2=2}
<child1 activetab={activetab}/>
<child2 activetab2={activetab2}/>
And I would like when the user changes the active tab from child 2 to update the state on the parent component, and then also handle the change on the child1 component.
child 1 code :
render() {
const activetab=this.props;
this.showimage1 = () => {
if (activetab === 1) {
return (
<img src={slide1} alt='' />
)
} else null;
}
return (
<div>
{this.showimage1()}
</div>
child 2 code :
constructor (props) {
super(props)
this.changetab= this.changetab.bind(this)
this.state={
activetab:1}
}
render () {
const activetab2=this.props;
changetab(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
})
}
}
return(
<div>
<button onClick={() => {
this.changetab(1)
}}
>tab1 </button>
</div>
So as you can see I want when the user changes the current tab from child 2 to pass the props in my parent component so that the child1 component knows which image to show depending on the tab. Anyone knows how to do it without rewriting everything in a single component?

Create a main component that renders the two component child 1 and 2 create only 1 source of truth means only 1 state to be pass to the child components as props.
export class MainComponent extends Component {
constructor (props) {
super(props)
this.changetab = this.changetab.bind(this)
this.state={
activetab: 0
}
}
changetab(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
})
}
render() {
return (
<div>
<ChildOne activetab={this.state.activetab} />
<ChildTwo activetab={this.state.activetab} changetab={this.changetab} />
</div>
)
}
}
// ChildOne Component pass state activetab as props
render() {
const { activetab } = this.props;
this.showimage1 = () => {
if (activetab === 1) {
return (
<img src={slide1} alt='' />
)
} else null;
}
return (
<div>
{this.showimage1()}
</div>
// ChildTwo Component
render () {
const { activetab, changetab } = this.props;
return(
<div>
<button onClick={() => {
this.changetab(1)
}}
>tab1 </button>
</div>

The parent component must have 2 function handlechange that you pass to your childs.
Will look something like that
// Parent
class Parent extends React.Component {
// Constructor
constructor(props) {
this.state = {
child1: 1,
child2: 0
};
}
handleChangeChild1(state) {
this.setState({ child1: state });
}
handleChangeChild2(state) {
this.setState({ child2: state });
}
render() {
return (
<div>
<Child1 onXChange={this.handleChangeChild1} />
<Child2 onYChange={this.handleChangeChild2} />
</div>
);
}
}
And in the children you do
class Child extends React.Component {
constructor(props) {
super(props)
}
handleChange(e) = () => {
this.props.onXChange
}
render() {
return (
<input onChange={this.handleChange} />
)
}
}
I recommend you read the doc

You can wrap the components in a parent component. Then you can pass a function from the parent to child 2 by attaching it to a prop. Child 2 can then call this function on a change.
In the parent:
render() {
const someFunction = (someVariable) => {
// do something
}
return(
<child2 somePropName={ this.someFunction } />
)
}
edit: removed .bind() from this example

Related

how to call function from component that is independent of each other

I have 3 components, one parent component which renders 2 child components. I need to access the function of the 1st child component from the 2nd child component.
Sample Code:
Parent Component:
class Main extends React.Component {
myRef: React.RefObject<any>;
constructor(props: any) {
super(props);
this.myRef = React.createRef();
}
return (
<div>
{/* some code */}
<ChildOne />
<ChildTwo />
</div>
);
ChildOne:
function ChildOne() {
const childOneFunction = () => {
console.log("Hello from child one");
};
return <div>{/* some code */}</div>;
}
}
ChildTwo:
function ChildTwo() {
useEffect(() => {
childOneFunction();
});
return <div>{/* some code */}</div>;
}
I need call the childOneFunction() from childTwo component. Is it possible without any 3rd party library like redux?
Maybe you can try with forwarding refs and useImperativeHandle.
Demo:
let ChildOne = React.forwardRef((props, ref) => {
React.useImperativeHandle(ref, () => ({
childOneFunction: () => {
console.log('Hello from child one');
},
}));
return <div>1</div>;
});
let ChildTwo = React.forwardRef((props, ref) => {
return (
<div
onClick={() => {
ref.current.childOneFunction();
}}
>
2
</div>
);
});
export default function App() {
const test = React.useRef();
return (
<div>
<ChildOne ref={test} />
<ChildTwo ref={test} />
</div>
);
}

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.

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