1

New to RJS, Trying to access my variable "txt" outside the Data.map callback where it was originally declared, how would I be able to do this and have full access to the variable?

CodeSandbox

import Data from "./names.json";
export default function App() {
  //want to access txt in here <==============
  // console.log(txt) and stuff after accessing it here
  return (
    <div className="App">
      {Data.map((post) => {
        var txt = post.Name;
        return <h1>{post.Name}</h1>;
      })}
    </div>
  );
}

Thanks

1
  • The same way you access it in the returned JSX? Data.map(...)? the problem is that Data is apparently an array, there isn't a single txt for you to access in the outer scope. Commented May 2, 2022 at 16:58

2 Answers 2

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );
}

6 Comments

sounds good, how would i go on about doing that?
@yumeii222 maybe you could explain in some more detail what it is you're trying to do. At the moment txt will always refer to the name of the last object in the loop which I'm sure isn't what you want. Maybe go back to the question and write what your intentions are for the code but it's a little unclear.
Wonderful, This seems to work although the names are being logged twice? codesandbox.io/s/stupefied-cerf-5j9vw2?file=/src/App.js
it could be a bug with codesandbox, the above code doesn't change the state so it should not rerender. like Andy said, if you provide us with your intentions with the code we may help you figure things out.
Yes, It appears to be a bug as it works fine in stackblitz. Thanks for the help :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.