2

Can we use props in function components in React, and if then, how?I was trying to do

console.log(this.props) 

above the return function in a function component but it kept giving me errors.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Salman Ahmed
  • 39
  • 1
  • 2
  • hi @Salman Ahmed, you use `this` to access props if it is a class based component, otherwise you access directly – buzatto Jun 23 '20 at 18:49
  • 1
    The [docs](https://reactjs.org/docs/components-and-props.html#function-and-class-components) is always a good place to start learning. – Brian Thompson Jun 23 '20 at 18:54
  • Does this answer your question? [React: Passing down props to functional components](https://stackoverflow.com/questions/39963565/react-passing-down-props-to-functional-components) – Michael Freidgeim Oct 06 '20 at 11:53

3 Answers3

3

Yes. You pass the props inside the function component directly (using props) like this:

function myFunc(props){
  console.log(props.content);
  return <div>{props.content}</div>;
}

assuming that the props that passes in has element content.

To clarify, there is no this in function components because they're not classes at all! Instead, you pass in props directly into the function.

In fact, it is probably the one of the first things that you learn in React. So if you're new, then I suggest the tutorial here.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34
1

Yes, like this,

the props are passed to the function component as the first argument

export default function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

here read this article it explains everything: https://medium.com/@PhilipAndrews/react-how-to-access-props-in-a-functional-component-6bd4200b9e0b

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Marik Ishtar
  • 2,899
  • 1
  • 13
  • 27
-1

You can access "this" keyword in class component ... In functional component you can access the props just by calling it as below.

import React from 'react'

const Printing=(props)=> {
    console.log(props)
    return (
        <div>
            
        </div>
    )
}
export default Printing
Fathma Siddique
  • 266
  • 3
  • 15