Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, Why the {} when passing props to stateless functional component?

My feeling is that the ({course}) syntax is extracting the property 'course' from the props object. Thereby making calls to 'course' properties inside the component more terse. If I passed props using the (props) syntax, in place of ({course}). I would then have to say 'props.course.authorId', for example.

Is my line of thinking correct? It would be great if you can expand on exactly whats happening here, and fill in any gaps.

import React, {PropTypes} from 'react';
import {Link} from 'react-router';

const CourseListRow = ({course}) => {
  return (
    <tr>
      <td><a href={course.watchHref} target="_blank">Watch</a></td>
      <td><Link to={'/course' + course.id}>{course.title}</Link></td>
      <td>{course.authorId}</td>
      <td>{course.category}</td>
      <td>{course.length}</td>
    </tr>
  );
};

CourseListRow.propTypes = {
  course: PropTypes.object.isRequired
};

export default CourseListRow;
like image 398
malexanders Avatar asked Jun 17 '16 16:06

malexanders


People also ask

What are the {} In React?

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. You need them when you want to use a JavaScript expression like a variable or a reference inside JSX.

Can we pass Props to functional component?

Of course, you can still pass props from parent to child with functional components but the big difference is that you'll need to declare them in your functional component callback just as you would with any other type of function. Now you can access those props.


1 Answers

You are correct. In ES6 syntax, the function signature

const CourseListRow = ({course}) => { ... }

is the same as the ES5 code

var CourseListRow = function(props) {
    var course = props.course;
    ...
}

This is called destructuring.

like image 122
nrabinowitz Avatar answered Nov 15 '22 04:11

nrabinowitz