nextra icon indicating copy to clipboard operation
nextra copied to clipboard

Global import for use on MDX files

Open yansusanto opened this issue 1 year ago • 8 comments

import {data, calc} from "@/components/data";

Is possible to import the above component globally for me to use {data, calc} across all .mdx files? Currently, I'm importing it at all .mdx files.

Any help is much appreciated.

yansusanto avatar Sep 30 '24 18:09 yansusanto

provide them via this option https://nextra.site/docs/docs-theme/theme-configuration#mdx-components and you will not need to import your components on every mdx file

dimaMachina avatar Sep 30 '24 19:09 dimaMachina

That's what I did but to no avail,

import React from "react";

import {data, calc} from "@/components/data";

export default {
	main: ({children}) => {
		return (
			{children}
		);
	},
	components: {
		data,
		calc,
		Bleed,
		Cards,
		Callout,
		Steps,
		Tabs,
	},
};

Am I missing something here?

yansusanto avatar Oct 01 '24 00:10 yansusanto

Does data and calc are react component?

dimaMachina avatar Oct 01 '24 00:10 dimaMachina

Yes, it is

export const data = {
	italy: {
		population: 1000,
	},
	america: {
		population: 2000,
	},
};

const parseNumber = (value) => {
	if (typeof value === "string") {
		return parseFloat(value.replace(/,/g, ""));
	}
	return value;
};

export const calc = (value, percentage, period = "Y") => {
	const parsedValue = parseNumber(value);
	let result = (parsedValue * percentage) / 100;

	return result.toLocaleString(undefined, {
		minimumFractionDigits: 0,
		maximumFractionDigits: 0,
	});
};

yansusanto avatar Oct 01 '24 00:10 yansusanto

They are not react components but object and function

dimaMachina avatar Oct 01 '24 00:10 dimaMachina

You are right, it is not. I guess I have to just import it into every mdx file.

yansusanto avatar Oct 01 '24 01:10 yansusanto

You can also try to assign them to globalThis in _app file and after they will be globally accessible

dimaMachina avatar Oct 01 '24 01:10 dimaMachina

Thank you for the pointer, @dimaMachina. You are the best!

import Inter from "@/components/font";
import "@/styles/app.scss";
import {data, calc} from "@/components/data";

export default function App({Component, pageProps}) {
	globalThis.data = data;
	globalThis.calc = calc;

	return (
		<Inter>
			<Component {...pageProps} />
		</Inter>
	);
}

yansusanto avatar Oct 01 '24 01:10 yansusanto