Plan - To render <List /> element in index.js. Displays the todo items the user has created.
Error -
./src/components/App.jsx
Attempted import error: './List' does not contain a default export (imported as 'List').
index.js -
import React from 'react';
import ReactDOM from 'react-dom';
import {List, Render} from './components/List';
import App from './components/App';
import '../src/styles.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
ReactDOM.render(
<Render />
, document.getElementById("list"));
List.jsx -
import react, { useRef } from 'react';
import ReactDOM from 'react-dom';
var todoItems = [];
const inputRef = useRef();
function onClick() {
todoItems.push(inputRef.current.value);
console.log("Pushed item in the array!");
render(inputRef.current.value);
}
function Render(value) {
todoItems.forEach(function a(item) {
<h1>{item}</h1>
});
}
function List() {
return (
<div className="mainbox">
<div className="inputdiv">
<input
type="text"
ref={inputRef}
placeholder="Enter Task..."
className="textbox"
id="taskName"
/>
<button className="button" onClick={onClick}>+</button>
</div>
</div>
);
}
export {List, Render};
I also tried -
export default List;
export {Render};
But it says useRef() cannot be called at the top level.
So I moved the inputRef to the List(), but it says that Render isn't defined.
Thanks!
P.S
After this import/export problem is solved, will the <h1> display?
function Render(value) {
todoItems.forEach(function a(item) {
<h1>{item}</h1>
});
}
EDIT -
index.html -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link font-family: "Montserrat" , sans-serif;
href="https://fonts.googleapis.com/css?family=McLaren|Montserrat&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="../src/styles.css">
<title>Mandy's Todo-List App!</title>
</head>
<body>
<div id="root">
<div id="list">
</div>
</div>
</body>
</html>
import { useState, useEffect } from 'react';
function App() {
const [value, setValue] = useState('');
const [list, setList] = useState([]);
function handleChange(event) {
setValue(event.target.value);
}
function addTodo() {
setList([...list, value]);
}
useEffect(() => setValue(''), [list]);
return (
<div className='App'>
<input value={value} onChange={handleChange}/>
<button onClick={addTodo}>Add</button>
{list.map((item, index) => <h1 key={index}>{item}</h1>)}
</div>
);
}
export default App;
Related
I'm New to nextjs and I ran into a problem I added a TawkTo and I feel like this is the reason of the error. I have imported dynamically my tawkto file in my _app.js file :
import '../styles/Home.css';
import 'bootstrap/dist/css/bootstrap.css';
import Navbar from './Navbar';
import Footer from './Footer';
import Script from 'next/script';
import Head from 'next/head';
import '#fortawesome/fontawesome-svg-core/styles.css';
import { SSRProvider } from '#react-aria/ssr';
import React from 'react';
import TawkTo from './Components/TawkTo';
import dynamic from 'next/dynamic';
function MyApp({ Component, pageProps }) {
const Countdown = dynamic(() => import("./Components/TawkTo"), {
SSR: false,
});
return (
<Head>
<link passhref="true" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossOrigin="anonymous" />
<Script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossOrigin="anonymous"></Script>
<link passhref="true" rel="preconnect" href="https://fonts.gstatic.com" crossOrigin />
</Head>,
<SSRProvider>
<React.StrictMode>
<Navbar />
<Component {...pageProps} />
<TawkTo />
<Footer />
</React.StrictMode>
</SSRProvider>
)
}
export default MyApp
and my TawkTo.js:
import React from 'react';
import { useEffect } from 'react';
const TawkTo = () => {
useEffect(() => {
// <!--Start of Tawk.to Script-->
var Tawk_API = Tawk_API || {},
Tawk_LoadStart = new Date();
(function () {
var s1 = document.createElement("script"),
s0 = document.getElementsByTagName("script")[0];
s1.async = true;
s1.src = 'https://embed.tawk.to/5d7e91079f6b7a4457e1cadb/default';
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin', '*');
s0.parentNode.insertBefore(s1, s0);
})();
// <!--End of Tawk.to Script-->
}, [])
return (
<div>
{/* empty div */}
</div>
)
}
export default TawkTo
and these are the console errors I'm getting:
a little help will be so much thankful :-)
In the following segment of code I call the Header module and React automatically adds the import to the Header module.
import Head from 'next/head'
import Header from '../components/Header'
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Header/>
<main className={styles.main}>
</main>
</div>
)
}
But at compile time React tells me it cannot resolve the Header module:
error - ./pages/index.tsx:3:0
Module not found: Can't resolve '../components/Header'
Header.jsx
import Image from 'next/image'
import { useEffect, useState } from 'react'
import Link from 'next/link'
const Header = () => {
const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
const handleScroll = () => {
if(window.scrollY > 0) {
setIsScrolled(true);
} else {
setIsScrolled(false);
}
}
window.addEventListener('scroll', handleScroll)
return () => {
window.removeEventListener('scroll', handleScroll)
}
}, [])
return (
<header>Header</header>
)
}
export default Header
Relative paths of index.jsx and Header.jsx:
\react\netflix-tailwind\components\Header.tsx
\react\netflix-tailwind\pages\index.tsx
I am trying to make a contact-manager-app from a YouTube video:
https://www.youtube.com/watch?v=0riHps91AzE&lc=Ugybk5M3ofjHsO8uHjd4AaABAg.9WHwkOL6qXV9WJu89p6VTV
Every time, I enter the inputs and click Add, the following error pops-up:
the screen-shot of the main page
I also get "6 moderate severity vulnerabilities" while downloading uuidv4. ( Put just in case, if it might help )
Also got "Module not found: Error: Can't resolve 'util' in 'C:\Users\loki\OneDrive\Desktop\ReactJS-YouTube\contact-app\node_modules\uuidv4\build\lib"
Here are all my files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
App.js
import React, { useState, useEffect } from "react";
import { uuid } from "uuidv4";
import "./App.css";
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";
function App() {
const LOCAL_STORAGE_KEY = "contacts";
const [contacts, setContacts] = useState([]);
const addContactHandler = (contact) => {
console.log(contact);
setContacts([...contacts, { id: uuid(), ...contact }]);
};
const removeContactHandler = (id) => {
const newContactList = contacts.filter((contact) => {
return contact.id !== id;
});
setContacts(newContactList);
};
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
return (
<div className="ui container">
<Header />
<AddContact addContactHandler={addContactHandler} />
<ContactList contacts={contacts} getContactId={removeContactHandler} />
</div>
);
}
export default App;
ContactList.js
import React from "react";
import ContactCard from "./ContactCard";
const ContactList = (props) => {
console.log(props);
const deleteContactHandler = (id) => {
props.getContactId(id);
};
const renderContactList = props.contacts.map((contact) => {
return(
<ContactCard contact={contact} clickHandler = { deleteContactHandler } key = { contact.id}/>
);
})
return(
<div className="ui celled list">
{renderContactList}
</div>
);
}
export default ContactList;
ContactCard.js
import React from "react";
import user from "../images/user.jpg";
const CardContact = (props) => {
const {id, name, email} = props.contact;
return(
<div className="item">
<img className="ui avatar image" src={user} alt="user" />
<div className="content">
<div className="header">{name}</div>
<div>{email}</div>
</div>
<i className="trash alternate outline icon"
style={{color:"red",marginTop:"7px"}}
onClick={() => props.clickHandler(id)}>
</i>
</div>
);
};
export default CardContact;
AddContact.js
import React from "react";
class AddContact extends React.Component {
state = {
name: "",
email: "",
};
add = (e) => {
e.preventDefault();
if (this.state.name === "" || this.state.email === "") {
alert("ALl the fields are mandatory!");
return;
}
this.props.addContactHandler(this.state);
this.setState({ name: "", email: "" });
};
render() {
return (
<div className="ui main">
<h2>Add Contact</h2>
<form className="ui form" onSubmit={this.add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<button className="ui button blue">Add</button>
</form>
</div>
);
}
}
export default AddContact;
From the uuidv4 npm page:
Most of the functionality of uuidv4 module is already included in uuid since version 8.3.0, so most of the functions of uuidv4 module have already been marked as deprecated.
So, importing uuidv4 module in your App.js is causing this error.
You can upgrade to the latest version of uuid library to get rid of this error.
Run these commands in the terminal in your project directory.
npm uninstall uuidv4
npm install uuid
And now, in App.js import uuid module instead of uuidv4
import { v4 as uuid } from 'uuid';
And now, you can use uuid() function to create UUIDs
To check more about uuid, you can see there documentation: https://github.com/uuidjs/uuid#quickstart
In your App.js:
On each useEffect (page renders) you are calling setContract , on useEffect below you are watching that contract as dependency , so it's rendering when contract is changing
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
I have tried multiple solutions that were suggested in MaterialUI and NextJS official examples and forums with no luck. My page is unable to use my MUI styles on the first render and I keep getting this error:
Warning: Prop `className` did not match. Server: "makeStyles-image-3 makeStyles-image-5" Client: "makeStyles-image-4 makeStyles-image-7"
My _document.tsx:
import React from 'react';
import Document, { DocumentContext, Head, Html, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '#material-ui/core/styles';
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<meta charSet="utf-8" />
<link rel="icon" href="/favicon.ico" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
static async getInitialProps(ctx: DocumentContext) {
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({ enhanceApp: (App) => (props) => sheets.collect(<App {...props} />) });
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps, styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()] };
}
}
My _app.tsx:
import '../styles/globals.css';
import type { AppProps } from 'next/app';
import React, { useEffect } from 'react';
import { CssBaseline, ThemeProvider } from '#material-ui/core';
import Head from 'next/head';
import { theme } from '../src/app/theme';
const App: React.FC<AppProps> = ({ Component, pageProps }) => {
useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side');
console.log(jssStyles?.parentElement?.removeChild(jssStyles));
jssStyles?.parentElement?.removeChild(jssStyles);
}, []);
return (
<React.Fragment>
<Head>
<title>My App</title>
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</React.Fragment>
);
};
export default App;
The solutions I've tried:
https://github.com/mui-org/material-ui/blob/0ff9cb54a9/examples/nextjs-with-typescript/README.md
https://github.com/hadnazzar/nextjs-with-material-ui/blob/master/README.md
Also many from StackOverflow similar posts (though none of the answers helped, so please do not mark this as a duplicate).
Used packages versions:
"#material-ui/core": "^4.12.3",
"next": "11.1.2",
"react": "17.0.2",
Is there anything that I'm missing here?
I am using material UI in NEXTJS and on first render sometimes its applying all the custom changes sometimes it doesn't. when it applying all those and click on link its breaking again and I did all the custom changes which mentioned https://github.com/mui-org/material-ui/blob/master/examples/nextjs here like creating custom _app.js and _document.js file
_app.js
import { useEffect, Fragment } from 'react';
import Head from 'next/head';
import PropTypes from 'prop-types';
import CssBaseline from '#material-ui/core/CssBaseline';
import { ThemeProvider } from '#material-ui/core/styles';
import theme from '../src/theme';
import "../styles/globals.css";
export default function MyApp({ Component, pageProps }){
useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side');
console.log(jssStyles);
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []);
const getLayout = Component.getLayout || ((page) => page)
return (<>
<Head>
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<CssBaseline />
{getLayout(<Component {...pageProps} />)}
</ThemeProvider>
</>)
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
pageProps: PropTypes.object.isRequired,
};
_document.js
import * as React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import theme from '../src/theme';
import { ServerStyleSheets } from '#material-ui/core/styles'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
{/* PWA primary color */}
<meta name="theme-color" content={theme.palette.primary.main} />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static-site generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
const originalRenderPage = ctx.renderPage;
const sheets = new ServerStyleSheets();
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => <App {...props} />,
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
};
};
any help would appreciated