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

345
Visualizações
How to export variable from react component?

I am using Mantine for a search bar and I need to get the wordcount of the text area. This is using Nodejs and React. I need to be able to export this value to use in a different file.

import React, { useState } from 'react';
import { TextInput, createStyles } from '@mantine/core';
var count = document.getElementById('count');

const useStyles = createStyles((theme, { floating }: { floating: boolean }) => ({
  root: {
    position: 'relative',
  },
  label: {
    position: 'absolute',
    zIndex: 2,
    top: 7,
    left: theme.spacing.sm,
    pointerEvents: 'none',
    color: floating
      ? theme.colorScheme === 'dark'
        ? theme.white
        : theme.black
      : theme.colorScheme === 'dark'
      ? theme.colors.dark[3]
      : theme.colors.gray[5],
    transition: 'transform 150ms ease, color 150ms ease, font-size 150ms ease',
    transform: floating ? `translate(-${theme.spacing.sm}px, -28px)` : 'none',
    fontSize: floating ? theme.fontSizes.xs : theme.fontSizes.sm,
    fontWeight: floating ? 500 : 400,
  },
  required: {
    transition: 'opacity 150ms ease',
    opacity: floating ? 1 : 0,
  },
  input: {
    '&::placeholder': {
      transition: 'color 150ms ease',
      color: !floating ? 'transparent' : undefined,
    },
  },
}
)
);
export function FloatingLabelInput() {
  const [focused, setFocused] = useState(false);
  const [value, setValue] = useState('');
  const { classes } = useStyles({ floating: value.trim().length !== 0 || focused });
  const uniqueid = "input";
  return(
    <TextInput
      id={ uniqueid }
      placeholder="Add anything you want to the book of the internet."
      required
      classNames={classes}
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      mt="md"
      onKeyUp={(e) => {
        var text = value.split(' ');
        var wordcount = 0;
        for (var i = 0; i < text.length; i++) {
          if (text[i] !== ' ') {
            wordcount++;
            }
          }
          count.innerText = wordcount;
        }
        }
      autoComplete="nope"
    />
      );
}

As you can see, it correctly outputs it into html, but returning inside the function doesnt work at all.

I tried exporting it, I tried returning it to the function but it doesn't see it. I tried exporting and using modules exports but that doesnt work either. Any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the following code snippet, my root component (called App) is responsible for keeping the app state, but it can give any piece of state to any of its children. It can also give state modifiers (setX functions) to its children, which is what I am demonstrating here:

function Input ({ setWordCount }) {
  function updateWordCount (event) {
    setWordCount(event.target.value.split(' ').length)
  }
  return <input type="text" onKeyUp={updateWordCount} />
}

function SomeOtherComponent ({ count }) {
  return (
    <span>: {count} words</span>
  )
}

function App () {
  const [wordCount, setWordCount] = React.useState(0)
  return (
    <p>
      <Input setWordCount={setWordCount} />
      <SomeOtherComponent count={wordCount} />
     </p>
  )
}
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.5/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.5/umd/react-dom.production.min.js"></script>
<div id="app" />

As you can see, the Input component can call the setWordCount function provided by its parent to change a piece of state. Then, the parent (App) can give that piece of state to any number of its children. Each component can live in a separate file too, this would still work…

I'm not sure if I understood your question correctly, but hopefully, this can give you ideas you can reuse in your own code?

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