So, I've tried setting up a component that creates breadcrumbs for React.
The code is here:
https://codesandbox.io/s/dreamy-microservice-mjxg2?fontsize=14
The error it's bringing back is that I'm mishandling the props.children.map, may any of you tell me why or how to fix it?
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Breadcrumb = ({props}) => {
const list = props.children.map((item) => (<li>{item}</li>));
return (
<ul>{list}</ul>
}:
const BreadcrumbItem = ({href, name}) => <div>{name}</div>;
function App() {
return (
<div className="App">
<Breadcrumb>
<BreadcrumbItem
href="/dashboard"
name="Dashboard"
/>
<BreadcrumbItem
href="/brand"
name="Brands"
/>
<Breadcrumb
href="/brand/new"
name="New brands"
/>
</Breadcrumb>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Change this:
const Breadcrumb = ({props}) =>
with
const Breadcrumb = (props) =>
Also, there is a typo in the App component. The last children is Breadcrumb, it should be BreadcrumbItem.
Working code is below:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Breadcrumb = (props ) => {
const list = props.children.map(item => <li>{item}</li>);
return <ul>{list}</ul>;
};
const BreadcrumbItem = ({ href, name }) => <div>{name}</div>;
function App() {
return (
<div className="App">
<Breadcrumb>
<BreadcrumbItem href="/dashboard" name="Dashboard" />
<BreadcrumbItem href="/brand" name="Brands" />
<BreadcrumbItem href="/brand/new" name="New brands" />
</Breadcrumb>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Related
I have used useEffect to fetch API & dispatch an action from inside it to update state. I am using context API, useReducer for state management and also react-router in this project.
In Header.js as soon as i import/use CartState and state variable (e.g. cart.length) then the app breaks down and items from api are not rendered and i get this error. In home.js also i am using state, but with only that part it does not give any error.
Below i am attaching two images, one with error and one where it is rendered when i remove CartState from header.js
Or you can see the codesandbox : https://codesandbox.io/s/serene-fast-297j3h?from-embed=&file=/
Website picture when CartState removed from header.js
Error message - website picture
Please tell me what is the issue here and what should be done.
index.js file:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter } from "react-router-dom";
import GlobalContext from './context/GlobalContext'
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<GlobalContext>
<App />
</GlobalContext>
</BrowserRouter>
</React.StrictMode>
);
App.js:
import "./App.css";
import Header from "./Components/Header";
import { Routes, Route } from "react-router-dom";
import Home from './Components/Home/Home'
import Cart from './Components/Cart'
function App() {
return (
<>
<Header />
<Routes>
<Route path="/" exact element={<Home/>}></Route>
<Route path="/cart" exact element={<Cart/>}></Route>
</Routes>
</>
);
}
export default App;
GlobalContext.js:
const CartContext = createContext();
const GlobalContext = ({children}) => {
const initialState ={
products: [],
cart: []
};
useEffect( ()=>{
const fetchData = async ()=> {
const res = await axios('https://fakestoreapi.com/products');
const resAdd = res.data.map((item)=> ({...item, inStock: faker.helpers.arrayElement([0,2,5,9,20]), fastDelivery: faker.datatype.boolean() }));
dispatch({type: 'API_CALL_SUCCESS', payload: resAdd});
// console.log(initialState);
}
fetchData();
}, [] )
const [state, dispatch] = useReducer(cartReducer, initialState );
console.log(state);
return (
<CartContext.Provider value={{state, dispatch}}>
{children}
</CartContext.Provider>
);
};
export default GlobalContext;
export const CartState = () => {
return useContext(CartContext);
};
Header.js (part of the code)
import CartState from "../context/GlobalContext";
const Header = () => {
const {
state: { cart },
dispatch,
} = CartState();
return (
<Navbar bg="dark" variant="dark" style={{ height: 100 }}>
<Container>
<Navbar.Brand>
<Link to="/">HOME</Link>
</Navbar.Brand>
<FormControl
className="m-auto"
style={{ width: 500 }}
type="text"
placeholder="Search here the product you want"
/>
<Nav>
<Dropdown
// alignRight
>
<Dropdown.Toggle variant="success">
<FaShoppingCart color="white" fontSize="25px" />
<Badge>
{cart.length}
{/* 1 */}
</Badge>
</Dropdown.Toggle>
Home.js:
import { CartState } from '../../context/GlobalContext'
import SingleProduct from '../SingleProduct';
import './styles.css'
import Filters from '../Filter/Filters';
const Home = () => {
const {state: {products}, } = CartState();
console.log(products);
return (
<div className="home">
<Filters />
<div className="productContainer">
{products.map( (item)=>
<SingleProduct prod = {item} key = {item.id} />
)}
</div>
</div>
)
}
export default Home
You need to modify below code line in Header.js file.
Actual:
import CartState from "../context/GlobalContext";
Expected/correct:
import {CartState} from "../context/GlobalContext";
Reason: CartState is not a default export.
In Header.js:
import CartState from '../context/GlobalContext';
this part of your code is wrong because you didn't export default your CartState function so you should import it like:
import {CartState} from "../context/GlobalContext";
In my App I have a HeaderLogo component, with <h1> containing animation (inside its head-main class). I would like to re-render this component to trigger animation, after onclick event in <NavLink>.
<NavLink> is inside DropdownMenu, which is inside MainNavi.
HeaderLogo
const HeaderLogo = () => {
return (
<header>
<h1 className="head-main">learning curve</h1>
</header>
)
}
export default HeaderLogo
Dropdown Menu
import { MenuItemContentSchool } from "./sub-components/MenuItemContentSchool"
import { useState } from "react";
import { NavLink } from "react-router-dom";
const DropdownMenu2 = () => {
const [click, setClick] = useState("");
const handleClick = () => {
setClick("hide-menu");
}
return (
<div className={`dropdown-holder-us ${click}`}>
{MenuItemContentSchool.map((item) => {
return (
<NavLink
to={item.link}
className='d-content-us'
onClick={handleClick}
key={item.title}
>
{item.title}
</NavLink>
)
} )}
</div>
)
}
export default DropdownMenu2
App
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HeaderLogo from "./components/HeaderLogo";
import NaviMain from "./components/NaviMain";
function App() {
return (
<Router>
<div className="App">
<HeaderLogo />
<NaviMain />
<Routes>
//...
</Routes>
</div>
</Router>
);
}
export default App;
NaviMain
import DropdownMenu2 from "./DropdownMenu2";
const NaviMain = () => {
return (
<nav>
<ul className="nav-main">
<li className="nav-main__button">
<a>school</a>
<DropdownMenu2 />
</li>
</ul>
</nav>
)
}
export default NaviMain
I do not know whether this will work or not but u can try the following solution:
set an id:
<h1 id="testing" className="head-main">learning curve</h1>
Change
const handleClick = () => {
setClick("hide-menu");
}
to
const handleClick = () => {
setClick("hide-menu");
let element = document.getElementById('#testing').
element.classList.remove("head-main");
element.classList.add("head-main");
}
Please let me know whether this solution works or not.
Fairly new to react here. I'm making a small recipe finder app with an api. After getting the data, I'm mapping through the results and displaying them in a component. What I want to do is display the details of each recipe through another component in another route. I'm not sure how to do this. I thought I could pass the mapped recipe through Link, but it's not working. Here is what I have so far.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React, { useState, useEffect} from "react";
import axios from "axios";
import { BrowserRouter as Router, Routes, Route, useNavigate} from "react-router-dom";
import "./App.css";
import RecipeList from "./RecipeList";
import Recipe from "./Recipe";
import Header from "./Header";
function App() {
const navigate = useNavigate();
const [recipes, setRecipes] = useState([]);
const [query, setQuery] = useState("");
const [search, setSearch] = useState("");
const APP_ID = "XXXXXXXXX";
const APP_KEY = "XXXXXXXXXXXXXXXXXXXXXX";
const url = `https://api.edamam.com/api/recipes/v2?type=public&q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`;
const getRecipes = async () => {
const res = await axios(url);
const data = await res.data.hits;
console.log(data);
setRecipes(data);
};
useEffect(() => {
getRecipes();
}, [query]);
const updateSearch = (e) => {
setSearch(e.target.value);
console.log(search);
};
const getSearchQuery = (e) => {
e.preventDefault();
setQuery(search);
setSearch("");
navigate("/recipes");
};
return (
<div className="App">
<Header />
<div>
<div className="container">
<form className="search-form" onSubmit={getSearchQuery}>
<input
className="search-input"
type="text"
value={search}
onChange={updateSearch}
placeholder="search by food name"
/>
</form>
</div>
</div>
<Routes>
<Route path="/recipes" element={<RecipeList recipes={recipes} />} />
<Route path="/recipes/:id" element={<Recipe recipes={recipes} />}/>
</Routes>
</div>
);
}
export default App;
RecipeList.jsx
import React from "react";
import { Link } from "react-router-dom";
const RecipeList = ({ recipes }) => {
return (
<div className="container">
<div className="grid-container">
{recipes.map(({ recipe }) => (
<Link to={`/recipes/${recipe.label}`}>
<img key={recipe.image} src={recipe.image} alt="" />
<p key={recipe.label}>{recipe.label}</p>
<p>{recipe.id}</p>
</Link>
))}
</div>
</div>
);
};
export default RecipeList;
Recipe.jsx
const Recipe = ({recipe}) => {
return (
<div>
<h1>{recipe.label}</h1>
</div>
)
}
export default Recipe
Am I even close???
You are passing the entire recipes array to both routed components.
<Routes>
<Route path="/recipes" element={<RecipeList recipes={recipes} />} />
<Route path="/recipes/:id" element={<Recipe recipes={recipes} />}/>
</Routes>
So Recipe can use the entire array and the id route match param to search the passed array and render the exact recipe by matching label.
import { useParams } from 'react-router-dom';
const Recipe = ({ recipes }) => {
const { id } = useParams();
const recipe = recipes.find(recipe => recipe.label === id); // *
return recipe ? (
<div>
<h1>{recipe.label}</h1>
</div>
) : null;
};
* Note: Since you call the route param id it may make more sense to us the recipe.id for the link.
{recipes.map(({ recipe }) => (
<Link to={`/recipes/${recipe.id}`}>
<img key={recipe.image} src={recipe.image} alt="" />
<p key={recipe.label}>{recipe.label}</p>
<p>{recipe.id}</p>
</Link>
))}
...
const recipe = recipes.find(recipe => recipe.id === id);
I've been struggling with my first solo proyect due to my lack of experience, here is the trouble I have:
I need to set a Link component (of react-router-dom) which takes me to another new page when I clicked the button. Thought that selection I need to pass to the link (and the context) the id so I can fetch the data from the API, but I cannot get an idea of how to make it works. This is the button link component:
Model.jsx
import React, { useState, useContext } from 'react';
import { BrowserRouter as Router, Switch, Route, Link, Redirect } from 'react-router-dom';
import FileModel from "../FileModel/FileModel";
import { ModelsContext } from "../../context/ModelsContext";
const Model = ({modelo}) => {
const { id, name, year, price, photo } = modelo;
const { guardarModelo } = useContext(ModelsContext);
const [display, setDisplay] = useState("btn-notdisplayed");
const showButton = e => {
e.preventDefault();
setDisplay("btn-displayed");
};
const hideButton = e => {
e.preventDefault();
setDisplay("btn-notdisplayed");
};
return (
<div
className="card"
onMouseEnter={e => showButton(e)}
onMouseLeave={e => hideButton(e)}
>
<div className="card-body">
<p className="card-name">{name}</p>
<p className="card-yearprice">{year} | $ {price}</p>
</div>
<img src={`https://challenge.agenciaego.tech${photo}`} className="card-image" alt={`Imagen de ${name}`} />
<Router>
<button
type="button"
className={display}
onClick={() => {
guardarModelo(modelo);
}}
><Link to={`/models/${modelo.id}`}>Ver Modelo</Link>
</button>
<Switch>
<Route exact path={`/models/${modelo.id}`} component={FileModel} />
</Switch>
</Router>
</div>
);
}
export default Model;
Then I obtained the data from a context:
ModelsContext.jsx
import React, { createContext, useState, useEffect } from 'react';
export const ModelsContext = createContext();
const ModelsProvider = (props) => {
//State de modelos
const [ modelo, guardarModelo ] = useState({});
const [ modelos, guardarModelos ] = useState([]);
const [ allModelos, guardarAllModelo ] = useState([]);
//Cargar un modelo
useEffect(() => {
const consultarAPI = async () => {
const api = await fetch("https://challenge.agenciaego.tech/models");
const modelos = await api.json();
const api2 = await fetch(`https://challenge.agenciaego.tech/models/${id}`);
const modelo = await api2.json();
guardarAllModelo(modelos);
guardarModelos(modelos);
guardarModelo(modelo);
}
consultarAPI()
}, []);
return (
<ModelsContext.Provider
value={{
allModelos,
modelo,
modelos,
guardarModelo,
guardarModelos
}}
>
{props.children}
</ModelsContext.Provider>
)
}
export default ModelsProvider;
Finally, I got the App.js from which I route the principal component, the idea Is to get with the Link to the new component called "FileModel.jsx" as a child component an so maintains the Navbar component.
App.js
import React from "react";
import Navbar from "./components/Nav/Navbar";
import Models from "./components/Models/Models";
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Logo from "./assets/img/logo.png";
import ModelsProvider from "./context/ModelsContext";
import ModelFooter from "./components/Models/ModelFooter";
function App() {
return (
<ModelsProvider>
<Router>
<nav className="navbar">
<img src={Logo} className="logo" alt="Ego Logo" />
<div className="menu-container">
<Link to={'/models'} className="menu-items">Modelos</Link>
<a className="menu-items">Ficha de modelo</a>
</div>
<div className="bottom-line"></div>
</nav>
<Switch>
<Route exact path='/models' component={Models} />
</Switch>
</Router>
<Navbar />
<ModelFooter />
</ModelsProvider>
);
}
export default App;
This is the fileModel.jsx so far:
import React, { useContext } from 'react';
import Navbar from "../Nav/Navbar";
import { ModelsContext } from "../../context/ModelsContext";
const FileModel = () => {
const { modelo } = useContext(ModelsContext);
console.log(modelo.id);
return (
<Navbar />
);
}
export default FileModel;
I hope to have explained my issue clear, and thanks so much to all you caring people!
Cheers!
Ps: Maybe you can find some things to refactor (I will need to check my code later), If you find something like that any help will be appreciated!
UPDATE
Due to Linda recommendation I merged the two contexts into one, and changed some lines of the code I wrote before, I cannot set the state to pass the solo model to the fileModel component and the Link still not working, I was thinking in a functions that can do it, I made another state, a single modelo, but when I click the button I got an error and undefined, because Idk how to set in the state the Id and so pass it to the API call, the terminal says that id in const api2 = await fetch(https://challenge.agenciaego.tech/models/${id}); is not defined.
I FINALLY SOLVED MY PROBLEM!!! I had to rellocate some elements between my component to make the api context take the id and pass it to the FileModel component, and change the Link router to the App.js, this is how I get to the solution:
App.js
import React from "react";
import Navbar from "./components/Nav/Navbar";
import Models from "./components/Models/Models";
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Logo from "./assets/img/logo.png";
import ModelsProvider from "./context/ModelsContext";
import ModelFooter from "./components/Models/ModelFooter";
import FileModel from "./components/FileModel/FileModel";
function App() {
return (
<ModelsProvider>
<Router>
<nav className="navbar">
<img src={Logo} className="logo" alt="Ego Logo" />
<div className="menu-container">
<Link to={'/models'} className="menu-items">Modelos</Link>
<Link to={`/models/1`} className="menu-items">Ficha del Modelo</Link>
</div>
<div className="bottom-line"></div>
</nav>
<Switch>
<Route exact path='/models' component={Models} />
<Route exact path='/models' component={Models} />
</Switch>
</Router>
<Navbar />
<FileModel />
<ModelFooter />
</ModelsProvider>
);
}
export default App;
Modelscontext.jsx
import React, { createContext, useState, useEffect } from 'react';
export const ModelsContext = createContext();
const ModelsProvider = (props) => {
//State de modelos
const [ modelo, guardarModelo ] = useState([]);
const [ modelos, guardarModelos ] = useState([]);
const [ allModelos, guardarAllModelo ] = useState([]);
const { id } = modelo;
//Cargar un modelo
useEffect(() => {
const consultarAPI = async () => {
const api = await fetch("https://challenge.agenciaego.tech/models");
const modelos = await api.json();
const api2 = await fetch(`https://challenge.agenciaego.tech/models/${id}`);
const modelo = await api2.json();
guardarAllModelo(modelos);
guardarModelos(modelos);
guardarModelo(modelo);
}
consultarAPI()
}, [modelo.id]);
return (
<ModelsContext.Provider
value={{
allModelos,
modelo,
modelos,
guardarModelo,
guardarModelos
}}
>
{props.children}
</ModelsContext.Provider>
)
}
export default ModelsProvider;
Model.js
import React, { useState, useContext } from 'react';
import { Link } from 'react-router-dom';
import { ModelsContext } from "../../context/ModelsContext";
const Model = ({modelo}) => {
const { name, year, price, photo } = modelo;
const { guardarModelo } = useContext(ModelsContext);
const [display, setDisplay] = useState("btn-notdisplayed");
const showButton = e => {
e.preventDefault();
setDisplay("btn-displayed");
};
const hideButton = e => {
e.preventDefault();
setDisplay("btn-notdisplayed");
};
return (
<div
className="card"
onMouseEnter={e => showButton(e)}
onMouseLeave={e => hideButton(e)}
>
<div className="card-body">
<p className="card-name">{name}</p>
<p className="card-yearprice">{year} | $ {price}</p>
</div>
<img src={`https://challenge.agenciaego.tech${photo}`} className="card-image" alt={`Imagen de ${name}`} />
<Link to={`/models/${modelo.id}`}><button
type="button"
className={display}
onClick={() => {
guardarModelo(modelo);
}}
>Ver Modelo
</button></Link>
</div>
);
}
export default Model;
FileModel.js (so far...)
import React, { useContext } from 'react';
import Navbar from "../Nav/Navbar";
import { ModelsContext } from "../../context/ModelsContext";
const FileModel = () => {
const { modelo } = useContext(ModelsContext);
const { photo, name } = modelo;
return (
<>
<Navbar />
<section>
<img src={`https://challenge.agenciaego.tech${photo}`} alt={`Imagen de ${name}`}/>
</section>
</>
);
}
export default FileModel;
Thanks to Linda for giving me the input to refactoring the context! cheers!
I am using react quizzes library:
https://codesandbox.io/s/react-quizzesexample-forked-2w1gj?file=/src/index.js:408-499
According to the documentation we can choose just these kind of builder items from menu that we want using toolBox.
I want to leave just Checkboxes in the menu but i didn't find a solution for this. Who can help?
function App() {
const [formdata, setFormData] = useState([]);
return (
<div className="App">
<QuizzBuilder onChange={setFormData} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
This package react-quizzes, looks not really great. Its final build not include all modules, and require importing things directly. But if you want, here's the solution:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { QuizzBuilder } from "react-quizzes";
import ToolBox from "react-quizzes/lib/ToolBox";
import "react-quizzes/lib/assets/antd.css";
const filteredToolBox = ToolBox().filter(el => el.field_name === "checkboxes_")
function App() {
const [formdata, setFormData] = useState([]);
return (
<div className="App">
<QuizzBuilder toolBox={filteredToolBox} onChange={setFormData} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Update #1
Added logic to override ToolBox label
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { QuizzBuilder } from "react-quizzes";
import QuizExample from "./QuizExample";
import "react-quizzes/lib/assets/antd.css";
import ToolBox from "react-quizzes/lib/ToolBox";
import { defaultMessages } from "react-quizzes/lib/translations/TranslatedText";
const filteredToolBox = ToolBox().filter(
(el) => el.field_name === "checkboxes_"
);
const messages = {
en: {
...defaultMessages.en,
"toolbox.checkboxes.name": "Here are Checkboxes"
}
};
function App() {
const [formdata, setFormData] = useState([]);
return (
<div className="App">
<QuizzBuilder
messages={messages}
toolBox={filteredToolBox}
onChange={setFormData}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);