Search code examples
reactjslifecycle

Passing props from function-components to class components ReactJS


Please help me.

How can I call the changeAutoSlide() function on the class component Slide. How to pass this function to Parent.

Here function View is Child and class Slide is Parent component.

I want to stop the interval on component Slide with life cycle

Thanks.

export default class Slider extends Component {
  componentDidMount() {
    this.autoSlide();
  }

  autoSlide = (interval) => {
    return interval;
  };

  render() {
    return <View autoSlide={this.autoSlide} />;
  }
}

const View = () => {
  const [slideIndex, setSlideIndex] = useState(1);

  const setIndex = () => {
    if (slideIndex > 0) {
      setSlideIndex(slideIndex + 1);
    }
    if (slideIndex === 20) {
      setSlideIndex(20 - slideIndex + 1);
    }
  };
  const changeAutoSlide = () => {
    const interval = setInterval(setIndex, 2000);
    return autoSlide(interval);
  };

  changeAutoSlide();  //// I want pass this func on component Slide

  return (
    <section>
      <h2>Hello React</h2>
    </section>
  );
};


Solution

  • You can manage the state (slideIndex) and its functions in the parent class component:

    export default class Slider extends Component {
      constructor(props) {
        super(props);
        this.state = {
          slideIndex: 1
        }
      }
      componentDidMount() {
        this.autoSlide();
      }
    
      setIndex = () => {
        if (this.state.slideIndex > 0) {
          this.setState({
            slideIndex: this.state.slideIndex + 1
          }) 
        }
        if (this.state.slideIndex === 20) {
          this.setState({
            slideIndex: 20 - this.state.slideIndex + 1
          }) 
        }
      };
    
      changeAutoSlide = () => {
        const interval = setInterval(setIndex, 2000);
        return this.autoSlide(interval);
      };
    
      autoSlide = (interval) => {
        return interval;
      };
    
      render() {
        return <View autoSlide={this.autoSlide} setIndex={this.setIndex} changeAutoSlide={this.changeAutoSlide} />;
      }
    }
    

    And from the Child component receive and use those props:

    const View = (props) => {
      // Use the props in this component like: 
      // props.changeAutoSlide()
      // props.autoSlide 
      // props.setIndex()
    
      return (
        <section>
          <h2>Hello React</h2>
        </section>
      );
    };
    

    Please take the time to read more about how React data flows: https://reactjs.org/docs/state-and-lifecycle.html#the-data-flows-down