3

I'm trying to pass functional component props by destructuring assignment method.

In this example below I have tried to use this concept but it doesn't work. the result of this code return empty and doesn't print that prop.

import React from 'react';
import { render } from 'react-dom';

const App = ({ username: name }) => (<h1>{username}</h1>)

render(
   <App name="Tom" />,
   document.getElementById('root')
);

Any ideas on how to handle this issue ?

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Salar Bahador
  • 1,433
  • 1
  • 14
  • 26

1 Answers1

7

Your're passing prop from App as name not username

change this

const App = ({ username : name })

to this

const App = ({ name: username })

import React from 'react';
import { render } from 'react-dom';

const App = ({ name: username }) => (<h1>{username}</h1>)

render(
   <App name="Tom" />,
   document.getElementById('root')
);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Tnx it's working now. why is it filled the name and username values in some kind of opossit syntax? – Salar Bahador Jun 02 '19 at 12:48
  • @SalarBahador the syntax is `{ propertyName : reference variable }` you can read [this](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses/54605288#54605288) for more info – Code Maniac Jun 02 '19 at 13:01
  • So this structure is different than other object structures in javascript? in the usual way, we say define object like : `obj = { key : value }` – Salar Bahador Jun 02 '19 at 13:04
  • @SalarBahador here you're not defining a object you're picking values from object – Code Maniac Jun 02 '19 at 13:06