1

Problem:- I have written a function named "getData()" in "App.js" and i am able to call it in "User.js". Code is written below.

But, What if i have written that "getdata()" function in "User.js" and i have to call it in "App.js". How can i do that? i am not able to do so.. please guide me.

App.js

import User from './User'
function App() {
  function getData() {
    alert("Hello from app component")
  }
  return (
    <div className="App">
     <User data={getData}/>
    </div>
  );
}
export default App: 

User.js

function User(props) {
        return(
            <div>
                <h1>User Component</h1>
                <button onClick={props.data}> Call Function</button>
            </div>
    export default User;
6
  • You shouldn't. It is best practice to decouple logic like getData from your UI code. Put the function in a seperate file and import it Commented Mar 30, 2022 at 11:56
  • How exactly i can import it? just like another component? i didn't get it. Please explain. Commented Mar 30, 2022 at 12:00
  • Put the function in a seperate file and export it, just like you did with your User and App component. You can then use the import statement like you did in App.js, when you imported the user component. Commented Mar 30, 2022 at 12:02
  • Read about the import and export statements here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… | developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 30, 2022 at 12:03
  • It is better to use redux for sharing values between components Commented Mar 30, 2022 at 12:10

1 Answer 1

1

App.js

import React, { useRef } from 'react';
import User from './User';

function App() {
  const childRef = useRef();

  return (
    <div className="App">
      <User ref={childRef} />
      <button onClick={() => childRef.current.getData()}>Call Function</button>
    </div>
  );
}
export default App;

User.js

import React, { forwardRef, useImperativeHandle } from 'react';

const User = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getData() {
      alert('Hello from user component');
    },
  }));

  return (
    <div>
      <h1>User Component</h1>
    </div>
  );
});
export default User;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.