ReactJS - How to use method from other component of other file? [duplicate] - reactjs

I have two components. I want to call a method of the first component from the second component. How can I do it?
Here is my code.
First Component
class Header extends React.Component{
constructor(){
super();
}
checkClick(e, notyId){
alert(notyId);
}
}
export default Header;
Second Component
class PopupOver extends React.Component{
constructor(){
super();
// here i need to call Header class function check click....
// How to call Header.checkClick() from this class
}
render(){
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default PopupOver;

You can do something like this
import React from 'react';
class Header extends React.Component {
constructor() {
super();
}
checkClick(e, notyId) {
alert(notyId);
}
render() {
return (
<PopupOver func ={this.checkClick } />
)
}
};
class PopupOver extends React.Component {
constructor(props) {
super(props);
this.props.func(this, 1234);
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;
Using statics
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}

You could do this to call a method of the child component from the parent component.
import React from 'react';
class Header extends React.Component {
constructor() {
super();
this.childComponentRef;
}
getChildComponent = (childComponent) => {
this.childComponentRef = childComponent;
this.childComponentRef.sayHi();
}
render() {
return (
<ChildComponent getChildComponent={this.getChildComponent} />
)
}
};
class ChildComponent extends React.Component {
componentDidMount () {
this.props.getChildComponent(this);
}
sayHi = () => {
alert("hi");
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;

Related

Create a removable React component without having to re-create remove function

I am looking to create a "delete-able" / removable React component that I can use in multiple different places.
From researching, I can see it is kind of an anti-pattern to create a component that deletes itself and the correct way to do things is for the parent to manipulate the child components rather than child components modifying themselves.
This has led me to write code somewhat along the following lines:
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: [ XXX ]
};
}
removeFunc = (index) => {
const test = this.state.data.filter((_,i) => i !== index);
this.setState({data: test});
}
render() {
return (
<div>
{this.state.data.map((el,i) =>
<ChildComponent removeFunc={() => this.removeFunc(i)}/>
)
}
</div>
);
}
}
export default ParentComponent;
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
removeFunc: props.removeFunc
};
}
render() {
return (
<div>
<button onClick={this.state.removeFunc}>Delete Me</button>
</div>
);
}
}
export default ChildComponent;
The issue I have with this is that I have to keep re-writing the removeFunc function in every parent component.
I am VERY new to React, so I'm just curious if there is there a better / different way to do this or is this the correct way?

React. How to call method of specific subchild in component tree

I'm starting to learn React and wonder how the following theoretical problem can be solved.
Suppose I have such components.
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
galaxyData:{}
};
}
handleGalaxyCommand(cmd) {
...
}
render() {
return (
<Galaxy galaxyData={this.state.galaxyData} />
);
}
}
class Galaxy extends React.Component {
render() {
return (this.props.galaxyData.sectors.map((sector) =>
<Sector sectorData={sector.sectorData} />
)
);
}
}
class Sector extends React.Component {
render() {
return (this.props.sectorData.ships.map((ship) =>
<Ship shipData={ship.shipData} />
)
);
}
}
class Ship extends React.Component {
constructor(props) {
super(props);
this.state = {
x: this.props.shipData.inialX,
y: this.props.shipData.inialY,
};
}
moveTo(x,y){
...
}
render() {
return <div x={this.state.x} y={this.state.y} id={this.props.shipData.id}/>
}
}
I wrote the code quickly for an example only, so I apologize for any syntax errors.
So the component tree looks something like this.
<Galaxy>
<Sector>
<Ship/>
...
<Ship/>
</Sector>
<Sector>
<Ship/>
...
<Ship/>
</Sector>
</Galaxy>
There may even be thousands of ships.
The ship has a "moveTo" method, which starts the Timer to change the x and y variables in the state, which causes the re-render, the move effect.
Let's assume that the Game component receives the command via the "handleGalaxyCommand" method to make the ship start moving.
How to call the "moveTo" method on a ship that interests me?
This is actually possible in react :) in a very simple way.
But this works only in class-based components (not functional or hooks).
Basically, you can call any child's methods from the parent if you access it's refs
Something like:
class Parent extends Component {
childRef = null;
componentDidMount() {
//via ref you can call it
this.childRef.myCustomMethod();
}
render() {
return <Child ref={ref => this.childRef = ref} />
}
}
class Child extends Component {
myCustomMethod() {
console.log("call me ");
}
render() {
return <div />;
}
}
Check this part of the docs for more details: https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component

Pass event through nested components bottom to top

While this question has been asked before I did not find an answer. I have components nested to the level of great grandchild and I don't know how to get the data from the bottom to the top.
<Parent/>
<Child/>
<GrandChild/>
<GreatGrandChild/>
See an example: fiddle
The great grandchild is a form and I want the input data to get to the parent at the top. I had it working when it was just nested one level deep, but now that it is deeply nested it does not work. I'm not sure how to even pass the event up two levels.
I've heard using redux is possible but I wonder if there is a way to avoid it. Or, how do I avoid the nesting? Even through they are all actually separate components should I just move them into one big component? This might work but seems like bad practice?
Very simplified, you could just pass the function through all the components:
class GreatGrandChild extends React.Component {
render() {
return (
<div>
<input onChange={this.props.onChange}/>
<h2>I'm the GreatGrandChild</h2>
</div>
)
}
}
class GrandChild extends React.Component {
render() {
return (
<div>
<h2>I'm the GrandChild</h2>
<GreatGrandChild onChange={this.props.onChange}/>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
<GrandChild onChange={this.props.onChange}/>
<h2>I'm the child</h2>
</div>
)
}
}
class Top extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
handleChildchange = (e) => {
console.log('child event on parent')
console.log(e.target.value);
}
render() {
return (
<div>
<Child onChange={this.handleChildchange}/>
<h2>I'm the parent</h2>
</div>
)
}
}
ReactDOM.render(<Top />, document.querySelector("#app"))
Redux is overkill for simple passing of props. You can pass props down through each child but it's easier to use the Context API like so:
Parent Component:
const MyContext = React.createContext('default');
export MyContext;
class Parent extends React.Component {
myFunction() {
//Do something here
}
render() {
return (
<MyContext.Provider value={this.myFunction}>
<ChildComponent />
</MyContext.Provider>
);
}
}
export default Parent;
Child Component:
import { MyContext } from './Parent';
class ChildComponent extends React.Component {
render() {
const { myFunction } = this.context;
return (
<div onClick={myFunction}>Click Me!</div>
);
}
}
ChildComponent.contextType = MyContext;
You can use the context as deep as you'd like, as long as you import it.
Simply pass a callback down from the parent via the props and make Sure it's passed all the way down to where you need it.
You also can pass props to your each child component in nesting and whenever values changed, you can call a parent function (nested) to get latest values in parent.

Accessing/Changing Parents State from Child Class using props (React)

I am trying to set state of the parent class with the child. But having trouble figuring out how to do this. I've abstracted away anything I deemed irrelevant to the question at hand. The issue is that I am
Class Parent extends Component {
constructor(props){
super(props)
this.state = {
foo: "bar"
}
}
coolMethod(n){
this.setState({foo: n})
}
render{
return(
<Child coolmethod={this.coolMethod} />
)
}
}
Class Child extends Component {
constructor(props){
super(props)
}
componentDidMount(){
let that = this;
videojs('my-player', options, function onPlayerReady() {
this.on('end',()=>{
that.props.coolMethod(<whatever string returns as a result of
this method>)
})
})
}
render{
return(
// irrelevant stuff to this question
)
}
}
Currently this code gives me "type error: this.setState is not a function"
If you want more info on videojs: http://videojs.com/ (though this is irrelevant to the question by itself, other than the fact that I reference it in my videojs call in componentDidMount of the child)
I assume the 2nd class is Class Child extends Component .... You need to bind this.coolMethod in your Parent constructor first.
Class Parent extends Component {
constructor(props){
super(props)
this.state = {
foo: "bar"
}
this.coolMethod = this.coolMethod.bind(this);
}
coolMethod(n){
this.setState({foo: n})
}
render{
return(
<Child coolmethod={this.coolMethod} />
)
}
}
Try this, tested working on my side, found two issues in the code
Javascript is case sensitive coolmethod is passed in to the Child, but you are trying to access coolMethod.
You need this > this.coolMethod = this.props.coolMethod.bind(this); in the constructor to inherit the setState function from the Parent, otherwise, this inside the coolMethod will be undefined.
import React, { Component } from 'react';
export default class Parent extends Component {
constructor(props){
super(props)
this.state = {
foo: "bar"
}
}
coolMethod(n){
this.setState({foo: n})
}
render(){
return(
<Child coolMethod={this.coolMethod} />
)
}
}
class Child extends Component {
constructor(props){
super(props)
this.coolMethod = this.props.coolMethod.bind(this);
}
render(){
return(
<button onClick={() => this.coolMethod("aabbcc")}>1</button>
)
}
}

Changing the state of a parent component using a function in the child compontent

I'm new to React, and I decided to build something simple like a Calculator to practice it's basics. However I have some trouble to understand the logic behind the information flow, and either there is a way for a child component to do the logic and update the parent in a natural way.
For example this is the basic structure of my calculator:
class Calculator extends React.Component {
render() {
return (
<div className="calculator-main">
<Screen numberOnScreen={this.state.numberOnScreen}/>
<NumberButton number={7} />
<NumberButton number={8} />
<NumberButton number={9} />
<OperatorButton operator="plus" view="-"/>
....
</div>
)
}
}
class Screen extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="screen">{new Intl.NumberFormat().format(this.props.numberOnScreen)}</div>
);
}
};
class NumberButton extends React.Component {
constructor(props) {
super(props);
}
render() {
const zeroClass = this.props.number === 0 ? " zero" : "";
return (
<button type="button" className={"number" + zeroClass}>{this.props.number}</button>
);
}
};
So I know that:
I can create the functions inside Calculator and pass it as a prop to
the buttons components, and call it onClick. (But it just feel weird).
Create an event listener in the Calculator compontent, create the
function inside the button component and pass the value via the event
trigger; (But it feels artificial).
Use some kind of global store?
But is there no natural react way to do this?
Thanks!
I think you want to know about React component communication. Here, I have implemented Child to Parent communication.
In this case Parent's state and state change method passes to child component through props. Then child can change parent's state use this method.
React Component Communication
//Parent component
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
content: 'Initial Content'
}
this.changeContent = this.changeContent.bind(this);
}
changeContent(event){
this.setState({
content: event.target.value
})
}
render(){
let { content } = this.state;
return <div>
<Child content={content} changeContent={this.changeContent}/>
<h1>{content}</h1>
</div>
}
}
// Child component
class Child extends React.Component{
constructor(props){
super(props);
}
render(){
let { content, changeContent } = this.props;
return <input value={content} onChange={changeContent}/>
}
}

Resources