How do I change the value of both components?

There are two components "My1" and "My2", there is a function myFunction(). The components do not share a common ancestor and are not interconnected. Both components are similar and refer to the same function. The question is how to make it so that when you click on the button of any of the components, the values change for both components. That is, both components should change the word "Did not click" to "Clicked" when you click on any button.

Here is the first component:

import React from 'react';
import Myfunction from "./myFunction.js" ; // здесь лежит функция

class My1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: "Не нажал" 
    };
  }
  NewStateOne = () => {
    Myfunction(this.state);
    console.log(this.state.name)
    this.setState({name: this.state.name})
  }
  render () {
    return(
      <div>
        <div>{this.state.name}</div>
        <button onClick={this.NewStateOne}>Click</button>
      </div>
    )
  }
}
export default My1;

Here's the second one component:

import React from 'react';
import Myfunction from "./myFunction.js" ; // здесь лежит функция

class My2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: "Не нажал" 
    };
  }
  NewStateTwo = () => {
    Myfunction(this.state);
    console.log(this.state.name)
    this.setState({name: this.state.name})
  }
  render () {
    return(
      <div>
        <div>{this.state.name}</div>
        <button onClick={this.NewStateTwo}>Click</button>
      </div>
    )
  }
}
export default My2;

Here is the function:

const Myfunction = (props) => {
  props.name = "Нажал";
  return props.name;
} 
export default Myfunction;

I am new to React and will be happy to hear any ideas and criticism.

Author: Kromster, 2020-08-28

1 answers

If I click on one button, and the text changes on the next one as well:

The state does not belong to buttons, it is shared, and is located in a component that is the ancestor of all buttons in the tree.

This common ancestor is a context provider -- puts its state in the context.

The buttons use useContext.

 0
Author: Sergei Kirjanov, 2020-08-28 18:26:31