stackjlei stackjlei - 3 months ago 18
React JSX Question

Rewrite react functional component in vanilla javascript

I'm having a hard time understanding how the functional component in React through es6 gets the props as an argument by placing it in an object. Is this part of es6's feature? Or is it part of React to magically pull the props through as an argument without having to refer to

this.props...
? If someone can rewrite the below component in vanilla js for me with a function (not React.createElement as Babel repl does), that would be very helpful.

const Repos = ({repos}) => {
return (
<div>
<h3> User Repos </h3>
<ul className="list-group">
{repos.map((repo, index) => {
return (
<li className="list-group-item" key={repo.name}>
<h4><a href={repo.html_url}>{repo.name}</a></h4>
<p>{repo.description}</p>
</li>
)
})}
</ul>
</div>
)
}

Answer

This is a destructuring assignment and part of the ES2015 spec. Repos is a function that expects an Object. When Repos is called it evaluates the destructuring pattern and assigns the result to its single argument:

const Repos = ({repos}) => {
  return repos;
}

const props = {repos: [1,2,3]};
const foo = {bar: "baz"};

console.log(Repos(props));
console.log(Repos(foo));

The name of the property (repos) and the name of the argument that is actually passed to Repos are the same, because the given destructuring pattern doesn't define a different one (in fact ({repos}) is shorthand for ({repos:repos})). However, a different name makes it clearer what is happening under the hood:

const Repos = ({repos:arg}) => {
  return arg;
}

const props = {repos: [1,2,3]};

console.log(Repos(props));

Please note that this has nothing to do with default parameters.