import React from 'react'
import HornedBeast from './HornedBeast'
import './Main.css'
export class Main extends React.Component {
render() {
return (
<div>
<h1>Main Page</h1>
imageArr.map((item,index)=>{
return(
<HornedBeast
key={index}
imgUrl={item.image_url}
title={item.title}
description={item.description}
/>
)
})
</div>
)
}
}
export default Main
You need to wrap your javaScript inside the JSX in { ... }
import "./styles.css";
import React from "react";
export default class Main extends React.Component {
imageArr = [];
render() {
return (
<div>
<h1>Main Page</h1>
{this.imageArr.map((item, index) => {
return (
<HornedBeast
key={index}
imgUrl={item.image_url}
title={item.title}
description={item.description}
/>
);
})}
</div>
);
}
}
function HornedBeast() {
return <div></div>;
}
Related
I call api in Home.js file with componentdidmount in class component and i want to render this data in child components with functional components.when i call api in every each child component, its work but when i try to call with props coming only empty array by console.log please help.
import React,{Component} from 'react'
import '../styles/home.css'
import axios from 'axios';
import Teaser from './Teaser'
import Second from './Second'
import Opening from './Opening'
import Menu from './Menu'
export default class Home extends React.Component {
state = {
posts: []
}
componentDidMount() {
axios.get("https://graph.instagram.com/me/media?fields=id,caption,media_url,permalink,username&access_token=IG")
.then(res => {
const posts = res.data.data;
this.setState({ posts });
})
}
render() {
return (
<>
<Teaser/>
<Second/>
<Opening/>
<Menu posts = {this.state.posts}/>
</>
)
}
}
import React from 'react'
import axios from 'axios';
function Menu(props) {
const {posts} = props;
console.log(props);
return (
<>
{posts && posts.map(
(post) =>
post.caption.includes('#apegustosa_menu') &&
post.children.data.map((x) => (
<div className="menu_item" key={x.id}>
<img className="menu_img" src={x.media_url} alt="image" />
</div>
)),
)}
</>
)
}
export default Menu
Here you go:
return (
<>
{
posts && posts.map(post => (
post.caption.includes("#apegustosa_menu") && post.children.data.map(x => {
return <img src={x.media_url} alt="img"></img>
})
))
}
</>
)
Im working on this app and when I run npm start I keep getting this error "TypeError: render is not a function". Ive tired everything from deleting the dependencies to running npm install. I even update react-router-dom and react-dom several times. Im at a lost here.
Here is the GitHub to the repository
https://github.com/Drayz/My-Book-Reads-App.git
Here is the Code:
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import "./index.css";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
); enter code here
App.js:
import React from 'react'
import { Switch,Route } from 'react-router-dom'
import Homepage from './windows/Homepage'
import Search from './windows/Search'
import Provider, {MyContext} from './Provider/'
import './App.css'
class BooksApp extends React.Component {
render() {
return (
<div className="app">
<Provider>
<MyContext.Consumer>
context
<Switch>
<Route exact path={"/"} render={ () => (
<MyContext.Consumer>
{context => <Homepage {...context} />}
</MyContext.Consumer>
)}/>
<Route exact path={"/search"} render={ () => (
<MyContext.Consumer>
{context => <Search {...context} />}
</MyContext.Consumer>
)}/>
</Switch>
</MyContext.Consumer>
</Provider>
</div>
)
}
}
export default BooksApp
Provider/index.js:
import React, { Component } from 'react';
export const MyContext = React.createContext();
export default class index extends Component {
constructor() {
super();
this.state ={
books:[],
currentlyReading:[],
wantToRead:[],
read:[],
addBooks: books => {
const currentlyReading = books.filter(book => book.shelf === 'currentlyReading');
const read = books.filter(book => book.shelf === 'read');
const wantToRead = books.filter(book => book.shelf ==='wantToRead');
this.setState({ books, currentlyReading, read, wantToRead });
},
moveBook: (book, newShelf, allShelfs) => {
console.log(newShelf);
const newBooks = this.state.books.map(allBooks => {
const foundID = allShelfs[newShelf].find(
bookID => bookID === allBooks.id
);
if (foundID) {
allBooks.shelf = newShelf;
}
return allBooks;
});
this.state.addBooks(newBooks);
}
};
}
render() {
return (
<MyContext.Provider value={{...this.state}}>
{this.props.children}
</MyContext.Provider>
)
}
}
SearchBook.js
import React, {Component} from 'react';
import {Link} from 'react-router-dom'
export default class Searchbooks extends Component {
render() {
return (
<div className="open-search">
<Link to={'/search'}>
Add a book
</Link>
</div>
)
}
}
Bookshelf.js
import React, {Component} from 'react';
import Book from './Book';
export default class Bookshelf extends Component {
render() {
return (
<div className="bookshelf">
<h2 className="bookshelf-title">{this.props.title}</h2>
<div className="bookshelf-books">
<ol className="books-grid">
{this.props.books &&
this.props.books.map(book => <Book key={book.id} {...book} moveBook={this.props.moveBook} />)}
</ol>
</div>
</div>
)
}
}
Book.js
import React, {Component} from "react";
import {update} from '../BooksAPI'
export default class Book extends Component {
handleChange = async e => {
e.presist()
try {
const shelf = e.target.value;
const book = this.props;
const result = await update(book, shelf);
this.props.moveBook(book, shelf, result);
} catch (error) {
console.log(error)
}
};
render() {
return (
<li>
<div className="book">
<div className="book-top">
<div className="book-cover"
style={{
width: 128,
height: 193,
backgroundImage:`url(${this.props.imageLinks ? this.props.imagesLinks.thumnail : ''})`
}}
/>
<div className="book-shelf-changer">
<select onChange={this.handleChange} value={this.props.shelf}>
<option value="move" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
<option value="none">None</option>
</select>
</div>
</div>
<div className="book-title">{this.props.title}</div>
<div className="book-authors">{this.props.authors ? this.props.author[0] : 'No Author'}</div>
</div>
</li>
)
}
}
Local_Host_Error, Local_Host_Error, Local_Host_Error
In App.js your consumer just says "context". I think what you meant was for that to be the variable that holds the data that comes from the provider. Right now it's just being read as a string and the render function freaks out because... well the logging isn't very good. In short when the component goes to render it hits a whole bunch of undefined and freaks out.
To fix this use:
{ context => {Your switch statement }}
In a React app I wrote a function in file1.js and use this function in file2.js
// file1.js
export const withPrefix = (Component) => (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
// file2.js
import { withPrefix } from '/path/to/file1.js'
let Toolbar = withPrefix(({prefix}) => ( // !error happens here
<Fragment>
<div style={{flexGrow: 1}}>
<Button><Link to={`${prefix}/create`}>New Artifact</Link></Button>
</div>
<Search style={{width: 200}}/>
</Fragment>
))
Then I got the error "TypeError: Object(...) is not a function". So I changed export withPrefix function
export function withPrefix(Component) {
return (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
}
And the error is gone, everything works. But I wonder why these two exports result differently?
And another question is if I want to export an arrow function in es6, is the 2nd export function style the only method?
Attachment 1 (DefaultView.js):
import React, {Component} from 'react'
import {Layout} from 'antd'
import Toolbar from './Toolbar'
import Content from './Content'
export const PrefixContext = React.createContext()
export function withPrefix(Component) {
return (props) => (
<PrefixContext.Consumer>
{prefix => <Component {...props} prefix={prefix}/>}
</PrefixContext.Consumer>
)
}
export default class DefaultView extends Component {
constructor(props) {
super(props)
this.state = {
view: props.defaultView
}
}
handleViewChange = (view) => {
this.setState({view})
}
render() {
const {prefix, views} = this.props
const {view} = this.state
return (
<PrefixContext.Provider value={prefix}>
<Layout>
<Toolbar view={view} views={views} onViewChange=
{this.handleViewChange}/>
<hr/>
<Content view={view}/>
</Layout>
</PrefixContext.Provider>
)
}
}
Attachment 2 (Summary.js)
import React, {Component, Fragment} from 'react'
import {Button, Input} from 'antd'
import {Link} from 'react-router-dom'
import ArtifactTable from './ArtifactTable'
import {withPrefix} from "./DefaultView"
const {Search} = Input
export const Toolbar = withPrefix(({prefix}) => (
<Fragment>
<div style={{flexGrow: 1}}>
<Button><Link to={`${prefix}/create`}>新建软件包</Link></Button>
</div>
<Search style={{width: 200}}/>
</Fragment>
))
class Summary extends Component {
state = {
data: []
}
componentDidMount() {
const {prefix} = this.props
console.log('prefix=' + prefix)
fetch(prefix).then(json => {
this.setState({data: json.content})
})
}
render() {
const {data} = this.state
return (
<div>
<ArtifactTable data={data}/>
</div>
)
}
}
export default withPrefix(Summary)
Attachment 3 (Toolbar.js)
import React from 'react'
import {Switch, Route} from 'react-router-dom'
import {Toolbar as SummaryToolbar} from './Summary'
import Create from './Create'
import Details from './Details'
import Edit from './Edit'
import {withPrefix} from "./DefaultView"
const Toolbar = withPrefix(({prefix, view, onViewChange}) => (
<div style={{background: '#fff', padding: 16, display: 'flex',
alignItems: 'baseline'}}>
<Switch>
<Route exact path={`${prefix}`} component={SummaryToolbar}/>
<Route exact path={`${prefix}/create`}
component={() => <Create.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
<Route exact path={`${prefix}/:id`}
component={() => <Details.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
<Route exact path={`${prefix}/:id/edit`}
component={() => <Edit.Toolbar view={view} onViewChange=
{onViewChange}/>}/>
</Switch>
</div>
))
export default Toolbar
Update It's indeed the cyclic dependency problem as #Bergi and #loganfsmyth said. After I moved out
the withPrefix export snippet into a new file Context.js from DefaultView.js, the problem resolved. But I still have one quesion. In a cyclic dependency circumstances, why export const f = () => () => {} different from export function f() => { return () => {} }. Is export const lazy evaluated than export function as #loganfsmyth said?
I want to know how I can pass a status from one page to another page for if used in the other way.
My first page Body.js (Which I handle the state):
import React from 'react';
import './Body.css';
import axios from 'axios';
import { Link } from "react-router-dom";
import User from './User';
class Body extends React.Component {
constructor (){
super();
this.state ={
employee:[],
employeeCurrent:[],
}
}
componentDidMount(){
axios.get('http://127.0.0.1:3004/employee').then(
response=>this.setState({employee: response.data})
)
}
getName = () => {
const {employee} = this.state;
return employee.map(name=> <Link className='link' to={`/user/${name.name}`}> <div onClick={()=>this.add(name)} key={name.id} className='item'> <img className='img' src={`https://picsum.photos/${name.name}`}></img> <h1 className='name'> {name.name} </h1></div> </Link>)
}
add = (name) => {
const nam = name;
this.state.employeeCurrent.push(nam)
console.log(this.state.employeeCurrent)
}
render(){
return(
<div className='body'>
{this.getName()}
</div>
)
}
}
export default Body;
My second page which I want to get the state called employeeCurrent:
import React from 'react';
import Header from './Header';
import Body from './Body';
class User extends React.Component {
constructor (props){
super(props);
this.props ={
employeeCurrent:[],
}
}
render(){
return(
<div >
{this.props.employeeCurrent}
</div>
)
}
}
export default User;
I'm using the React Router, it looks like this:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './Home';
import User from './User';
const AppRouter = () => (
<Router>
<div className='router'>
<Route exact path="/" component={Home}/>
<Route path="/user/:id" component={User}/>
</div>
</Router>
);
export default AppRouter;
My project is:
Home page, where you have users, obtained from the API, all users have attributes (name, age, city and country). Saved in employeeCurrent variable:
What I want is: grab these attributes from the clicked user and play on the user page:
Someone would can help me PLEASE?????
Like I explained earlier, you need to lift the state up:
AppRouter (holds the state and passes it to children)
class AppRouter extends React.Component {
state = {
employeeCurrent: [],
employee: []
};
componentDidMount() {
axios
.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
}
add = name => {
this.setState(prevState => {
const copy = prevState.employeeCurrent.slice();
copy.push(name);
return {
employeeCurrent: copy
};
});
};
render() {
return (
<Router>
<div className="router">
<Route
exact
path="/"
render={props => (
<Home
{...props}
add={this.add}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
<Route
path="/user/:id"
component={props => (
<User
{...props}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
</div>
</Router>
);
}
}
Body and User (receive parent state as props together with updater functions):
class Body extends React.Component {
getName = () => {
const { employee, add } = this.props;
return employee.map(name => (
<Link className="link" to={`/user/${name.name}`}>
{" "}
<div onClick={() => add(name)} key={name.id} className="item">
{" "}
<img
className="img"
src={`https://picsum.photos/${name.name}`}
/>{" "}
<h1 className="name"> {name.name} </h1>
</div>{" "}
</Link>
));
};
render() {
return <div className="body">{this.getName()}</div>;
}
}
class User extends React.Component {
render() {
// you will need to map employeeCurrent somehow
return <div>{this.props.employeeCurrent}</div>;
}
}
I have this code:
Sidebar.jsx
class Sidebar extends Component {
render() {
return (
<div className="sidebar">
{ this.props.children }
</div>
);
}
}
class Item extends Component {
render() {
return (
<div>
<b> { this.props.name } </b>
</div>
);
}
}
export { Sidebar, Item };
index.js
export {default as Header} from './Header';
export {default as Footer} from './Footer';
export {default as Sidebar, Item} from './Sidebar';
app.jsx
import { Sidebar } from '../components';
class App extends Component {
render() {
return (
<div>
<Header/>
<Sidebar>
<Sidebar.Item name='item1' />
<Sidebar.Item name='item2' />
<Sidebar.Item name='item3' />
</Sidebar>
<Footer/>
// ...
The error that I get is:
TypeError: Cannot read property 'Item' of undefined
How I can multiple export component in index.js and call from another file? I'm sure that Header and Footer work correctly because I have only one class in that file.
function Sidebar(props) {
return (
<div className="sidebar">
{ props.children }
</div>
);
}
function Item (props) {
return (
<div>
<b> { this.props.name } </b>
</div>
);
}
Sidebar.Item = {Item}
export default Sidebar
Then you can use it like this
import Sidebar from './Sidebar.js'
...
return (
<Sidebar>
<Sidebar.Item />
</Sidebar>
)
If you're using class based components, you can remove the curly braces
class Sidebar extends Component {
render() {
return (
<div className="sidebar">
{this.props.children}
</div>
);
}
}
class SidebarItem extends Component {
render() {
return (
<div>
<b> {props.name} </b>
</div>
);
}
Sidebar.Item = SidebarItem;
export default Sidebar;
I learned this practice from a coworker that saw it in semantic ui's table here.
Have you tried
import { Item } from '../components';
and then use it:
<Item name='item1' />