Home > Mobile >  Exporting / Importing a Const from a React Component
Exporting / Importing a Const from a React Component

Time:12-10

I have read several Stack Overflow questions and articles trying to find a simple example of what I'm trying to do, but everything seems overly complicated. I just want to be able to export a const that I created in a function in one React component, and import for use into another React component. For example:

Component containing the const I want to export, FirstArticle:

function Articles() {
  const FirstArticle = document.querySelector('.article');
  console.log(FirstArticle) // <div >Article 1</div>

  return (
    <div>
      <div >Article 1</div>
      <div >Article 2</div>
      <div >Article 3</div>
    </div>
  )
}

export default Articles;

Component into which I want to import the const FirstArticle:

import Articles, { FirstArticle } from "./Articles";

function Preview() {
  return (
    <div>
      {FirstArticle} // Would expect to see: <div >Article 1</div>
    </div>
  )
}

export default Preview;

I have tried a few different things - moving the const FirstArticle to outside of the Articles function to make it more "global", putting the const in a separate function and exporting/importing that function (works but it imports the whole function on the other component and I'm not sure how to parse out just the FirstArticle const), and exporting the const in the export default line along with the function (didn't work).

I'm reading that I may need to use useState. As I'm new to React I'm not too familiar with this. Is useState the solution I need to look into?

CodePudding user response:

Why not use different files for the different components? Something like:

// useArticles.js
export function useArticles() {
  return [...something]; // the array of articles
}
// Article.js
export function Article(props) {
  const {article} = props;
  return <div >
    {/* ...here you render a single article */}
  </div>;
}
// Articles.js
import { Article } from './Article';
import {useArticles} from './useArticles';
export function Articles() {
  const articles = useArticles();
  return <div>
    {articles.map(article => <Article key={article.id} article={article} />)}
  </div>;
}
// Preview.js
import {Article} from './FirstArticle';
import {useArticles} from './useArticles';
function Preview() {
  const articles = useArticles();
  const firstArticle = articles[0];
  return (
    <div>
      <Article article={firstArticle} />
    </div>
  )
}

export default Preview;

Btw, if you are new to react and you don't know useState I suggest you to learn the react hooks before proceed (particularly useState and useEffect).

Also, in react you should always think to the data first and after how to render them, it will be better to avoid getting data from render components when it's possible.

  • Related