Passing props to JSX tags in React

Author
By Darío Rivera
Posted On in RegExp

In a previous article, we built our first Hello World application in React. In this post, we will explore how props can pass information to JSX tags, which allows us to dynamically set HTML attributes using JavaScript expressions.

Props are the information that you pass to a JSX tag. For instance, you can pass props to <img> such as src, width, hegiht and others. The different props you can pass to JSX tags conform to the HTML standard. Let's take a look at the following example:

function MyImage() {
  const image = "https://picsum.photos/200/300?grayscale";

  return (
    <img src={image} width="80" />
  );
}

Notice how the src attribute receives a JavaScript variable using curly braces {}. This syntax allows us to use JavasScript variables or expressions that will be interpreted by React. 

The CSS class is a special prop referenced as className because class is a reserved JavaScript keyword.

function Logo() {
  return (
    <img className="logo" src="https://picsum.photos/200/300?grayscale" />
  );
}

On the other hand, CSS Styles are passed as JavaScript objects. Notice how the native css propery border-radius becomes borderRadius in the following example:

function StyledImage() {
  const style = {
    width: "100px",
    borderRadius: "8px"
  };

  return (
    <img style={style} src="https://picsum.photos/200/300?grayscale" />
  )
}

Boolean attributes become more natural in JSX as they are literally JavaScript boolean values.

function MyButton() {
  const disabled = true;

  return <button disabled={disabled}>Click>/button>;
}

Let's see how some of these concepts look in CodePen.


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.