React: Passing down props to functional components React: Passing down props to functional components javascript javascript

React: Passing down props to functional components


You would need to pass down each prop individually for each function that you needed to call

<CreateProfile  onFirstNameChange={this.firstNameChange}   onHide={close}  show={this.state.showModal}/>

and then in the CreateProfile component you can either do

const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}

with destructuring it will assign the matching property names/values to the passed in variables. The names just have to match with the properties

or just do

const CreateProfile = (props) => {...}

and in each place call props.onHide or whatever prop you are trying to access.


I'm using react function component
In parent component first pass the props like below shown

import React, { useState } from 'react';import './App.css';import Todo from './components/Todo'function App() {    const [todos, setTodos] = useState([        {          id: 1,          title: 'This is first list'        },        {          id: 2,          title: 'This is second list'        },        {          id: 3,          title: 'This is third list'        },    ]);return (        <div className="App">            <h1></h1>            <Todo todos={todos}/> //This is how i'm passing props in parent component        </div>    );}export default App;

Then use the props in child component like below shown

function Todo(props) {    return (        <div>            {props.todos.map(todo => { // using props in child component and looping                return (                    <h1>{todo.title}</h1>                )            })}        </div>      );}


An addition to the above answer.

If React complains about any of your passed props being undefined, then you will need to destructure those props with default values (common if passing functions, arrays or object literals) e.g.

const CreateProfile = ({  // defined as a default function  onFirstNameChange = f => f,  onHide,  // set default as `false` since it's the passed value  show = false}) => {...}