score:1

Accepted answer

afaik you can't because text is scoped to the map function and you can't access it outside of it. you can try putting it in a state or make a function and make it an argument of that function from inside the map function.

import data from "./names.json";
import {usestate} from 'react'
export default function app() {
  //want to access txt in here <==============
  // console.log(txt) and stuff after accessing it here
  const [text,settext] = usestate()
  function gettext(text) {
    console.log(text) // this function gets called in every instance of the map loop
    //you can run your logic here to find specific information and then set it to the state like in this example
    if (text === "mytext") {
        settext(text)
    }
  }
  
  return (
    <div classname="app">
      {data.map((post) => {
        var txt = post.name;
        gettext(txt) // will run and recieve the var txt every instance
        return <h1>{post.name}</h1>;
      })}
    </div>
  );
}

score:2

many ways, but the usestate hook is pretty solid especially if you want to take advantage of react's speed.

import data from "./names.json";

export default function app() {
  const [ txt, settxt ] = usestate(""); // sets it to an empty string to begin with
  
  useeffect(() => {
    console.log(txt); // every time the 'txt' variable changes, log it
  }, [ txt]); // << react calls this a dependency and will only run this function when this value changes.

  console.log(txt); // also accessible here

  return (
    <div classname="app">
      {data.map((post) => {
        settxt(post.name); // this updates the 'txt' variable from earlier ^^
        return <h1>{post.name}</h1>;
      })}
    </div>
  );
}

if all that is too long-winded, just keep your txt variable outside of the function component, and react won't reset it every loop. you'll still be able to access its value anywhere in the file. example:

import data from "./names.json";
let txt = "";

export default function app() {
  return (
    <div classname="app">
      {data.map((post) => {
        txt = post.name;
        return <h1>{post.name}</h1>;
      })}
    </div>
  );
}

Related Query

More Query from same tag