Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
React's props with the same name as their value

Can we pass props to a component that has the same name and value implicitly?

Example: Let's say that I have a variable called x: const x = 1; and I have a component that has a prop called x. Can I pass it this variable as value implicitly? like that: <div x/>?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Booleans can be passed implicitly to the component as @Ajay also pointed out in comments, like

<div x />

which is basically equivalent to

<div x={true} />

However, if your variable is something other than a boolean, then you need to write it like

<div x={x} />

Or if you have a number of such props, you can form an object like

const cmpProps = {
   x,
   y,
   foo,
   bar
}

and pass them using Spread attributes like

<Comp {...cmpProps} />
over 4 years ago · Santiago Trujillo Relatório

0

I had a slight epiphany when reading these answers. Since in ES6+ you can add an existing variable to an object like this:

const x = 42;
const obj = { x, y: 1337 };
console.log(obj); // result { x: 42, y: 1337 }

That means you can add a named prop to a React component like:

const x = 42;
const elm = <MyComponent {...{x}} />;
over 4 years ago · Santiago Trujillo Relatório

0

You can't, a prop with no assigned value (<div x />) is a shortener for (<div x={true} />) (as Ajay Varghese pointed out);

Passing the same variable name would be <div x={x} />

If you need to pass multiple values directly in JSX props you can use the JSX Spread Attributes.

const divProps = { x: 1, y: 2 };
...
<div {...divProps} />

It is often used to pass all props from parent to children.

You can also override a prop by assigning it after the spread :

<div {...divProps} x=3 />
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda