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>
);
}
Data.map(...)? the problem is that Data is apparently an array, there isn't a singletxtfor you to access in the outer scope.