Home > Enterprise >  Getting data as variable in react component
Getting data as variable in react component

Time:12-27

I have to get data from another file but as a variable, i'll declare data source in main file. Below is code for component and main file. The problem is in component file because declaring variable like that doesn't working.

Component code:

  const Sylwetka = ({bg, dataSource}) => {
  return (
    <div>
      <Navbar />
      <div className={`h-[50vh] p-4 ${bg}`}>
        {{dataSource}.map((data) => {
          return (
            <div>
              <h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1>
            </div>
          );
        })}
      </div>
    </div>
  )
}

export default Sylwetka

Main app code:

const App = () => {
  return (
    <div className="lato text-white">
    <BrowserRouter>
      <Routes>
        <Route path='/*' element={<Home />}/>
        <Route path='/dahmer' element={<Sylwetka bg='dahmer-bg' dataSource={dahmerData}/>}/>
      </Routes>
    </BrowserRouter>
    </div>
  );
}

export default App;

CodePudding user response:

  • You have a syntax error, change "{dataSource}.map" to "dataSource.map".

  • Don't forget to declare your "dahmerData".

Give a feedback in comment and put your post to solved if the code below solves your problem.

Component code :

const Sylwetka = ({bg, dataSource}) => {
  return (
    <div>
      <Navbar />
      <div className={`h-[50vh] p-4 ${bg}`}>
        {dataSource.map((data) => {
          return (
            <div>
              <h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1>
            </div>
          );
        })}
      </div>
    </div>
  )
}

export default Sylwetka

Main app code :

const dahmerData = []; // your dataSource variable ...

const App = () => {

  return (
    <div className="lato text-white">
    <BrowserRouter>
      <Routes>
        <Route path='/*' element={<Home />}/>
        <Route path='/dahmer' element={<Sylwetka bg='dahmer-bg' dataSource={dahmerData}/>}/>
      </Routes>
    </BrowserRouter>
    </div>
  );
}

export default App;

CodePudding user response:

It looks like the issue in your component code is caused by the curly braces around dataSource. These curly braces are causing the dataSource variable to be treated as a JavaScript object literal, rather than a variable.

To fix this issue, you can simply remove the curly braces around dataSource:

const Sylwetka = ({bg, dataSource}) => {
  return (
    <div>
      <Navbar />
      <div className={`h-[50vh] p-4 ${bg}`}>
        {dataSource.map((data) => {
          return (
            <div>
              <h1 className='text-5xl font-extrabold opacity-60'>{data.title}</h1>
            </div>
          );
        })}
      </div>
    </div>
  )
}

export default Sylwetka

With this change, the dataSource variable will be correctly interpreted as a variable, and the map function will be able to iterate over its elements.

  • Related