React Importing a component folder [duplicate] - reactjs

This question already has answers here:
Is it possible to import modules from all files in a directory, using a wildcard?
(14 answers)
Closed 5 years ago.
I currently have my project folder as such
app
- node_modules
- public
- src
- Assets
- Components
- profiles
- homepage
- gulpfile
In my homepage component, I am trying to import the whole directory of profiles into an object like this (dynamically load each component as needed, but not all components will be loaded)
import Comps from '../profiles/';
also
import * as Comps from '../profiles/;
but I get an error in the compiler saying Module not found: Can't resolve '../profile.
I want to make it clear that profiles is a folder with components, and I want to select all components to call dynamically in my app.js file.
Why is this happening?

Do you have several components in one js file, if so - you could do something like this:
Profiles.js:
import React from 'react';
export const ViewA = () => {
return( <div>A VIEW</div>)
};
export const ViewB = () => {
return( <div>B VIEW</div>)
};
export const ViewC = () => {
return( <div>C VIEW</div>)
};
export const ViewD = () => {
return( <div>D VIEW</div>)
};
App.js:
import React, { Component, PropTypes } from 'react'
import * as Profiles from './Profiles';
class App extends Component {
render(){
return (
<div>
<Profiles.ViewA/>
<Profiles.ViewB/>
<Profiles.ViewC/>
</div>
)
}
}
export default App;

Related

i'm get this error, i don't know what to do, "TypeError: render is not a function"

okay, so i'm new to the react world, and i was learning about the react useContext, i followed exactly what a tutorial on youtube did, i'm trying to build a little project, i tried following his steps and then i hit an error while trying to use the state i literally want it to be accessible accross my app components, inside my app i've created various componenents and also various responsibility that combines all the reusuable components and do a specific task with it. i'm now trying to access my context from my GETCLICKEDIMAGES file, below are my steps
StateContext.jsx file
import React, { useState, createContext } from "react";
export const StateContext = createContext();
export const StateProvider=(props)=> {
//all the components in this app will share this state.
const [names, setNames] = useState([{ name: "Zucci Daniel! its working" }]);
return (
<StateContext.Provider value={"helo"}>{props.children}</StateContext.Provider>
);
}
App.js
import React, { Component } from "react";
import BigWrapper from "./justComponents/BigWrapper/BigWrapper";
import NavBar from "./justComponents/NavBar/NavBar";
import MainContainer from "./justComponents/MainContainer/MainContainer";
//below are the various responsibilities component
import SEARCHANDDISPLAY from "./Responsibilities/SEARCHANDDISPLAY/SEARCHANDDISPLAY";
import { GETCLICKEDIMAGES } from "./Responsibilities/GETCLICKEDIMAGES/GETCLICKEDIMAGES";
import { StateContext } from "./StateContext/StateContext";
class App extends Component {
render() {
return (
<StateContext>
<BigWrapper>
<NavBar />
<MainContainer>
<SEARCHANDDISPLAY />
<GETCLICKEDIMAGES />
</MainContainer>
</BigWrapper>
</StateContext>
);
}
}
export default App;
GETCLICKEDIMAGE.jsx
import React,{useContext} from "react";
import ClickedImageHolderDiv from "../../justComponents/ClickedImageHolderDiv/ClickedImageHolderDiv";
import Figure from "../../justComponents/Figure/Figure";
//you wanna use the stateContext right? import the context here as so;
import { StateContext } from "../../StateContext/StateContext";
//this is responsible for getting the clicked images and displaying them in full details
/**
a DIV to hold the FIGURE
*/
export const GETCLICKEDIMAGES=()=> {
const value =useContext(StateContext);
return (
<ClickedImageHolderDiv>
<h2>{value}</h2>
<Figure useThisStyle={{ height: "100%" }} />
</ClickedImageHolderDiv>
);
}
i don't know if i'm missing something, or something's changed, pls help.
Import StateProvider in your app.js instead of stateContext

How can I import browser module in next.js without dynamic import [duplicate]

This question already has an answer here:
Why am I getting ReferenceError: self is not defined when I import a client-side library?
(1 answer)
Closed 11 months ago.
import Highlighter from "monaco-jsx-highlighter";
this import in next.js gives "document not found" error. So i tried to dynamically import
import dynamic from "next/dynamic";
const Highlighter = dynamic(import("monaco-jsx-highlighter"), { ssr: false });
However dynamic import returns Loadable Component. I checked the next-github and looks like dynamic import works only for components. But import Highlighter from "monaco-jsx-highlighter". Highlighter is actually a class and needs to be initialized as :
const highlighter = new Highlighter()
How can I use this module in next.js without dynamic import?
Seems like the problem is that highlighter has client side only code and cannot run on server with SSR. You could import it regularly into some other component, like HighlighterWrapper and then import HighlighterWrapper dynamically into your main component where you need it, then it should work.
import Highlighter from "monaco-jsx-highlighter";
export const HighligherWrapper = (props) => {
// Make instance here or outside
const highlighter = useMemo(() => new Highlighter(),[]);
// Do whatever you want here with highlighter instance
return <div>Something</div>;
}
export default HighligherWrapper;
import dynamic from "next/dynamic";
const HighligherWrapper = dynamic(()=> import("./HighligherWrapper"), { ssr: false });
const Page() {
// Now you can use it in your code and it won't break SSR
return (
<div>
<HighligherWrapper />
</div>
);
}
Try smt. like this:
/ClientSideComponent.js:
import Highlighter from "monaco-jsx-highlighter";
export default function ClientSideComponent(props){
// Write here the Highlighter logic.
return <Highlighter />;
}
/page.js:
import dynamic from "next/dynamic";
const ClientSideComponent = dynamic(()=> import("./ClientSideComponent.js"), { ssr: false });
function Page(props) {
return <ClientSideComponent />
}
I solved the issue with the vanilla dynamic import instead of next.js dynamic import.
let jsxHighlighter = null;
import("monaco-jsx-highlighter").then((allMonacoSyntaxHighlighter) => {
jsxHighlighter = allMonacoSyntaxHighlighter.default;
});

import components from create-react-library subfolder

I have been trying to use create-react-library and so far it works, but I can only import components successfully from index.js. If I try to make another file , I recieve an import error.
The file structure is as such
example
\ Node Module
\ public
\ src
| App.js
| index.js
...
src
\ Patterns
| index.js
| button.js
Currently I can only successfully import components from index.js of the main src. Is there a way to successfully import components from folders such as Patterns or another file?
\ App.js ( example )
Importing button gives me an error "Cant import button from neo"
import React from 'react'
import { ExampleComponent,Button} from 'neo'
import {Test} from 'neo/Patterns';
import 'neo/dist/index.css'
const App = () => {
return (
<>
<Test />
<Button text='Click me' />
<ExampleComponent text="Create React Library Example 😄" />
</>
)
}
export default App
Please check if this is what you're trying to achieve.
index.js will be exporting required components like this,
import ExampleComponent from './ExampleComponent/ExampleComponent';
// ExampleComponent is placed inside a folder named ExampleComponent
import Patterns from './Patterns/Patterns';
// Patterns is placed inside a folder named Patterns
export { ExampleComponent, Patterns };
Patterns.js can look like this,
import React from 'react'
const Patterns = () => {
return <div>Patterns Component sample</div>
}
export default Patterns;
ExampleComponent.js can look like this,
import React from 'react'
import styles from './styles.module.css'
const ExampleComponent = ({ text }) => {
return <div className={styles.test}>Example Component: {text}</div>
}
export default ExampleComponent;
In the consumer level (in this case, example folder), in any jsx, like App.js you can refer those exported components like,
import { ExampleComponent, Patterns } from 'neo'
return (
<Patterns />
)

React - how to make an export component private to its directory?

Is it possible to limit the import of React components to it's own directory? So it is only possible to import inside the same directory?
For example I have the following dir strutcture:
src/
apps/
myapp.js
/table
table.js
table-row.js
The file table-row.js has the following component
export const TableRow = ({row, index}) => {
return <TableRow> ... </TableRow>
};
How to make TableRow private to /table dir, so I can not import outside this directory? But the table/table.js can import?
You cant actually do this, but a pattern that I like to follow is to do something like
src
components
MyComponent
MyComponent.jsx
PrivateHelperComponent.jsx
index.js
where the components resemble the follow:
//MyComponent.jsx
const MyComponent = () => {
return (
<div>
...
<PrivateHelperComponent />
</div>
)
>
export default MyComponent
//PrivateHelperComponent.jsx
const PrivateHelperComponent = () => {
return (
<div>
...
</div>
)
>
export default PrivateHelperComponent
//index.js
export { default } from "./MyComponent"
...Now the interface for importing from <...>/components/MyComponent is "clean", and you can only import the "default" component.
Of course, nothing stops you from doing import PrivateHelperComponent from "<...>/components/MyComponent/PrivateHelperComponent", but at least in my opinion it clear what components are meant to be imported/reused and what aren't
There is no access modifier for exports in JS (all exports are accessible to all modules; aka public), so you cannot make an export private to its directory.
You can’t do that. But if you really want to make it private put table row (with no export) and table in the same file.

Using marked in react

I want to use marked in reactjs as described in the reactjs docs.
<div>{marked(mystring)}</div>
I use babel so I import marked like this:
import { marked } from 'marked';
Unfortunately the import statement does not work. marked is not defined.
How do I have to import marked here, so that I can use it?
Here's one way to use marked with React:
Ensure that you've installed marked
Include marked in your project's package.json file:
// package.json
{
dependencies: {
react: "^17.0.0",
marked: "^4.0.0",
},
}
Import marked in your .jsx (or related) file:
import { marked } from "marked";
Use the dangerouslySetInnerHTML approach as shown in the example below:
import React from "react";
import { marked } from "marked";
class MarkdownExample extends React.Component {
getMarkdownText() {
var rawMarkup = marked.parse("This is _Markdown_.");
return { __html: rawMarkup };
}
render() {
return <div dangerouslySetInnerHTML={this.getMarkdownText()} />;
}
}
The dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!
Alternative (Safe)
If you don't want to use dangerouslySetInnerHTML and safely render HTML. Try marked-react, which internally uses marked to render the html elements as react components
npm i marked-react
import Markdown from "marked-react";
const MarkdownComponent = () => {
return <Markdown>{rawmarkdown}</Markdown>;
};
Another alternative is react-markdown
Here is another way of using marked with React Hooks:
Create your MarkedConverter component
import { useState } from 'react'
import marked from 'marked'
export const MarkedConverter = () => {
const [markedVal, setMarkedVal] = useState(
'# Welcome to my React Markdown Previewer!'
)
return <div dangerouslySetInnerHTML={createMarkUp(markedVal)}></div>
}
Create Markup function and pass the value from MarkedConverter Component
export const createMarkUp = (val) => {
return { __html: marked(val) }
}
Finally you can import MarkedConverter Component to any of your Component
With the marked-wrapper react-marked-markdown:
import { MarkdownPreview } from 'react-marked-markdown'
export default ({ post }) => (
<div>
<h1>{ post.title }</h1>
<MarkdownPreview value={ post.content }/>
</div>
)
If you just want to import marked:
import marked from 'marked';
Then call the function in your component:
marked('# Markdown');
Here's an example on how to use marked with react:
Install marked with NPM : npm i marked
import it in your react app (this example is created with create-react-app), and using it
example of a react component using "marked"
result in the browser :
preview

Resources