,

[Resolved] How to pass props to child Function Component in React

You can get the props passed in parent to child function component by defining props in the function parameter as shown below: App.js Function Component import React, { useState, useEffect } from ‘react’; import ‘./style.css’; import Test from ‘./test.component’; export default function App() { let [countplus, setCountplus] = useState(0); let [countminus, setCountminus] = useState(0); function…

By.

•

min read

You can get the props passed in parent to child function component by defining props in the function parameter as shown below:

App.js Function Component

import React, { useState, useEffect } from 'react';

import './style.css';
import Test from './test.component';

export default function App() {
  let [countplus, setCountplus] = useState(0);
  let [countminus, setCountminus] = useState(0);

  function incrementCount() {
    let _count = countplus + 1;
    setCountplus(_count);
  }
  function decrementCount() {
    let _count = countminus - 1;
    setCountminus(_count);
  }

  return (
    <div>
      <h1>Parent App Function Component</h1>

      <button onClick={incrementCount}>Count++</button>
      <button onClick={decrementCount}>Count--</button>

      <Test pluscount={countplus} minuscount={countminus} />
    </div>
  );
}

We have two states for PlusCount and MinusCount. We are passing them into the Test function compoennt as props.

 

Child Function Component

In the Test function component, we will get the props as arguments:

import './style.css';
import React from 'react';

export function Test(props) {
  return (
    <div>
      <h2>Test Child Function Component</h2>
      <h4>Plus Count: {props.pluscount}</h4>
      <h4>Minus Count: {props.minuscount}</h4>
    </div>
  );
}

export default Test;

 

In Action on StackBlitz:

Leave a Reply

Your email address will not be published. Required fields are marked *