Home > OS >  React, Calling a function from antoher component
React, Calling a function from antoher component

Time:07-13

As stated in the question I want to call a function declared in another component. Here's some example data,

function BookingTable() {
const renderTableData = (startId) => {
    let id = startId;
    }
}

export default BookingTable;

How do i access the renderTableData from another component?

CodePudding user response:

If the function should be accessible is the child component of the component which has the function. Then you can pass the function through props.

But the best option for this is context api. With that you can access the function in multiple components.

Context api helps you share the states and functions of a component with other components inside the particular project.

In Filecontext.jsx you can see createContext which helps you in creating a context.

In App.jsx, we have created the states and functions which has to be shared among the components and wrapped the components which can access the datas with that context by importing it.

In Formcomponent.jsx, I am using useContext to use the states and functions created in the App.jsx.

Filecontext.jsx

import { createContext } from 'react'
export const Filecontext = createContext({});

App.jsx

import { Filecontext } from './Contexts/Filecontext';
import { useState } from 'react'

function App() {
  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [mobileno, setMobileno] = useState("")
  const showAlert = () => {
    alert(`Hello ${name}`);
  }

  return (
    <div className="App">
      <Filecontext.Provider value={{ name, setName, email, setEmail, mobileno, setMobileno, showAlert }}>
        <Formcomponent />
        <Listcomponent />
      </Filecontext.Provider>
    </div>
  );
}

export default App;

Formcomponent.jsx

import { Filecontext } from '../Contexts/Filecontext';
import { useContext } from 'react'

export default function Formcomponent() {
    const { setName, setEmail, setMobileno, showAlert } = useContext(Filecontext)

    return (
        <>
            <div className="form-group">
                <label>Name : </label>
                <input type="text" onChange={(e) => { setName(e.target.value) }} />
            </div>
            <div className="form-group">
                <label>Email : </label>
                <input type="email" onChange={(e) => { setEmail(e.target.value) }} />
            </div>
            <div className="form-group">
                <label>Mobile No : </label>
                <input type="number" onChange={(e) => { setMobileno(e.target.value) }} />
            </div>
            <div className="form-group">
                <input type="submit" value="submit" onClick={() => { showAlert() }} />
            </div>
        </>
    )
}

CodePudding user response:

function BookingTable() {
    const renderTableData = (startId) => {
        let id = startId;
    }
    return (
        <BookingTable2 renderTableData={renderTableData} />
    )
}

export default BookingTable;
const BookingTable2 = ({renderTableData}) => {
    const onClickHandler = () => {
         renderTableData()
    }
   
    return (
         <button onClick={onClickHandler}>Calling func from child component</button>
    )
}

export default BookingTable;

CodePudding user response:

Bear in mind that React FC are just JS functions that return JSX (in most cases) so you can't access variables that were declared inside of them from outside of the component. The solution to that problem would be to pass the function as props to the child components.

CodePudding user response:

You can use Render Props https://reactjs.org/docs/render-props.html you need to call from parent comp to child comp

  • Related