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

184
Visualizações
JSX passing an object to the value of a jsx tag in React

I'm trying to pass an object to a value of an jsx tag in react

  • I set the value of tag option to an object

  • onChange i got the value in tag <Form.Select> and set the local state with the value

  • I console logged the local state but it returned [object Object]

  • I did JSON.stringify on it this way:

    console.log(JSON.strigify(obj))

    It returned : "[object Object]"

what am I doing wrong?

here is the state of the react component:

const [selectedOp, setSelectedOp] = useState()

here is the console.log:

console.log(selectedOp)
console.log(JSON.stringify(selectedOp))

and this is the html code:

<Form.Select onChange={e => setSelectedOp(e.target.value)} className='b' style={{ display: 
    'inline-block' }} size="lg" aria-label="Default select example">
     <option>Click to choose message</option>
     {mainNotifications.map((n, i) =>
     <option key={i} name="selectMessage" value={{message:n.message,type:n.type}}>hey this is an option tag </option>
     )}
</Form.Select>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

your value is a string type, not an object otherwise it prints as [object, object] so you need to stringify your object value

value=JSON.stringify({message:n.message,type:n.type})

check the example below

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [val, setVal] = useState();

  const changeHandler =value => {
    console.log(value);
    setVal(value);
  
  };

  return (
    <div>
      <select onChange={e => changeHandler(e.target.value)}>
        <option value={JSON.stringify({value: 'one', type: 'number' })} >none</option>
        <option value={JSON.stringify({value: 'one', type: 'number' })}>one</option>
      </select>
      {val&&console.log(JSON.parse(val))}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

value={{message:n.message,type:n.type}}

You cannot set objects as values, this will make the value itself be a string of [object Object], which is what you see(when you stringify your state, it was already [object Object] before), you can store a index or identifier value, and search in an array for the object, if you want to JSON stringify it, it would have to be done on the value of the options as well

const mainNotifications = [
  { message: "my msg", type: 1 },
  { message: "my msg 2", type: 3 }
];

export default function App() {
  const [selectedOp, setSelectedOp] = React.useState(null);
  const onChange = (e) => {
    setSelectedOp(
      mainNotifications.find((_, i) => e.target.value === i.toString())
    );
  };

  React.useEffect(() => {
    console.log(selectedOp);
  }, [selectedOp]);

  return (
    <select onChange={onChange}>
      <option>Click to choose message</option>
      {mainNotifications.map((n, i) => (
        <option key={i} name="selectMessage" value={i}>
          {n.message}
        </option>
      ))}
    </select>
  );
}

https://codesandbox.io/s/red-resonance-iyrnb

about 4 years ago · Juan Pablo Isaza 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