React adding favorites with checkboxes - html

Objects
Favourites
im trying to do a website witch react and i use an api to recieve data. The Data i recieved gets put into a list and then i produce a button for every item in this list. Now i also produce a check box for every item in the list, but the production is in a seperate component. what i want to do ist that, if the checkbox of one item gets checked, the item should be stored in a cache and put out again as an button on a seperate page. My Question now is how do i do that?
Thank you in advance.
This is where i produce the checkbox:
import React from "react";
export default function Favcheck() {
return (
<>
<div class="favcheck">
Favorit
<input type="checkbox" name="name" class="checkbox" id="heart" />
</div>
</>
);
}
this is where the buttons are made:
import axios from "axios";
import * as React from "react";
import Favcheck from "./favcheck.jsx";
import Mensapage from "./mensapage.jsx";
import site from "./home.jsx";
export default function Mensbuttons(props) {
return (
<>
<div class="formcontainer">
<form method="get" action="/mensapage" id="mensaform">
<button type="submit" class="mensabutton" key={props.key}>
<div class="mensatext">{props.name}</div>
</button>
<br></br>
<Favcheck />
</form>
</div>
</>
);
}
and this is where the buttons are used:
import React,{ useState, useEffect } from "react";
import axios from 'axios';
import Nav from "./nav.jsx";
import Mensbuttons from "./mensbuttons.jsx";
export default function Home(props) {
let site="test";
const[posts,setPosts] = useState([])
useEffect(()=>{
axios.get('https://openmensa.org/api/v2/canteens?near[lat]=52.517037&near[lng]=13.38886&near[dist]=15')
.then(res =>{
setPosts(res.data)
})
.catch(err =>{
console.log(err)
})
},[])
console.log(posts);
return (
<>
<Nav />
<div class="header">
<h1>Mensen</h1>
</div>
{posts.map((list) => {
return <Mensbuttons name={list.name} key={list.id} />;
})}
</>
);
}

here are some mockup pictures
i want to get specific objects to the favourites page by checking the checkbox
here are the favourites
here are the buttons with checkboxes

Related

how can I add props inside class in html which already exists

I want to add a class from another file as a prop, but I am not able to do it.
file 1
import React from 'react'
const Button = (props) => {
return (
<div>
<button class={"btn btn-primary" props.classes } type="submit" >{props.name}</button>
</div>
)
}
export default Button
file 2:
<Button name="Sign Up" classes="me-sm-0"></Button>
You just have to pass the desired className in the props just like below:
const Button = (props) => {
return (
<div>
<button className={`btn btn-primary ${props.className}`} type="submit" >{props.name}</button>
</div>
)
}
And this will be the Component used:
<Button name="Sign Up" className="me-sm-0"></Button>
I have read your article carefully.
I think your attempt to pass classes as props of the Button component worked really well.
If there is one disappointment, the syntax of react jsx is wrong.
In react jsx, the class property of html should be written as className.
And use ...${regexp}, one of the new features in es6.
I attach the code below.
--App.js
import React from 'react';
import './style.css';
import Button from './Button';
export default function App() {
return (
<div>
<Button name="Sign Up" classes="me-sm-0" />
</div>
);
}
--Button.js
import React from 'react';
export default function Button(props) {
return (
<div>
<button className={`btn btn-primary ${props.classes}`} type="submit">
{props.name}
</button>
</div>
);
}

React mapping fetched data

I'm trying to fetch some data from my database with some simple to-dos. However I cant seem to map them out into a list on my site.
I keep getting errors like: todoFromServer.map is not a function or that todoFromServer is not an array etc.
My current code looks like this:
import apiFacade from "../api/apiFacade";
import React, { useState, useEffect } from "react";
import {Form, FormGroup, Label, Input, Button} from "reactstrap"
export default function SecurePage() {
const [todoFromServer, setTodoFromServer] = useState("Waiting...");
useEffect(() => {
apiFacade.getTodo().then((data) => setTodoFromServer(data));
}, []);
return (
<div className="container-fluid padding">
<div className="row">
<div className="col-3"></div>
<div className="col-6 text-center">
<Form>
<FormGroup>
<h3 className="mt-5">Todos</h3>
<Input type="text" placeholder="Enter Todo"></Input>
</FormGroup>
<Button type="submit">Add</Button>
</Form>
<div>
{todoFromServer.map(() => (
<div>{todoFromServer.todoText}</div>
))}
</div>
</div>
</div>
</div>
);
}
The data I trying to fetch should come out as json looking like this:
I'm kind of lost.. Hope someone can help me out
to be clear - I want the data mapped out on a list with a delete button next to it...
const [todoFromServer, setTodoFromServer] = useState([]); // <=== initialize this as an empty array.
useEffect(() => {
apiFacade.getTodo().then((data) => setTodoFromServer(data)); // Make sure data returned from Promise resolve is indeed an array
}, []);
You want to read todoText of each todo's inside your array item so you would do something like this.
{todoFromServer.length ? todoFromServer.map((todo) => (
<div>{todo.todoText}</div>
)) : "Waiting..."}
For additional reference, take a look at Array.map usage here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

React JSON - Display data in a Card Slider

I have a local JSON file which I've converted to Javascript.
I am able to fetch the data by importing the JS file into my App.js.
This is my App.js file:
import React, { Component } from "react";
import CardData from "./data/db";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
CardData
};
}
render() {
return (
<div>
{this.state.CardData.map(cards => (
<div className="card">
<span>{cards.title}</span>
<br />
<span>{cards.subtitle}</span>
<br />
</div>
))}
</div>
);
}
}
export default App;
I want to be able to show 3 Cards, and then have the option to slide across to the remaining cards.
Something like this
However I am only able to show it in one div, is there a way to do it in the way I've called the JSON or is there a way to separate the JSON data by their ID?
Since you are looking for a simpler way to achieve the same result I would suggest switching your App to a stateless component, as it is never updating/using any state value :
import React from "react";
import CardData from "./data/db";
import "./App.css";
const App = props => (
<React.Fragment> //A fragment will not appear in your DOM
{CardData.map(({ title, subtitle }, index) => ( //Deconstructs each cards
<div className="card" key={index}>
<span>{title}</span>
<br />
<span>{subtitle}</span>
<br />
</div>
))}
</React.Fragment>
)
export default App;
But this component will never be able to render anything else than this specific JSON file, if you want it to be more generic, you should send your data via the component's props :
import React from "react";
import "./App.css";
const App = ({ cards }) => (
<React.Fragment>
{cards.map(({ title, subtitle }, index) => (
<div className="card" key={index}>
<span>{title}</span>
<br />
<span>{subtitle}</span>
<br />
</div>
))}
</React.Fragment>
)
export default App;
And in your parent component :
import CardData from "./data/db";
const Parent = props => <App cards={CardData}/>
You should also not forget about keys when mapping elements, as every mapped component should have a unique and persistent key.

Show dialog in React - Material UI

I am learning ReactJS. I would like to display dialog when someone clicks on the icon.
Here is the code:
import React, { Component } from 'react';
import { GridList, GridTile } from 'material-ui/GridList';
import FlatButton from 'material-ui/FlatButton';
import Info from 'material-ui/svg-icons/action/info';
import { fullWhite } from 'material-ui/styles/colors';
import Dialog from 'material-ui/Dialog';
import RaisedButton from 'material-ui/RaisedButton';
(... class stuff, handleClose, handleOpen etc.)
showDialoga() {
const actions = [
<FlatButton
label="Cancel"
primary
onClick={this.handleClose}
/>,
<FlatButton
label="Submit"
primary
keyboardFocused
onClick={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Dialog" onClick={this.handleOpen} />
<Dialog
title="Dialog With Actions"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
The actions in this window were passed in as an array of React objects.
</Dialog>
</div>
);
}
render() {
console.log(this.props);
return (
<div style={styles.root}>
<GridList
cellHeight={180}
style={styles.gridList}
padding={10}
>
{this.props.movieData.map(tile => (
<GridTile
key={tile.original_image}
title={tile.title}
actionIcon={<FlatButton
icon={<Info color={fullWhite} />}
style={style}
onClick={() => this.showDialoga()}
/>}
>
<img src={tile.original_image} />
</GridTile>
))}
</GridList>
</div>
);
}
}
I am able to pass other function like () => console.log('I am clicked') to onClick although I am not able to pass that showDialoga().
Any idea what is the problem?
I do not believe that's how you are supposed to use dialog.
Instead of passing return of React component on click, try setting the dialog opened state to be true/false. Also do not forget to bind this to the class level if you are using functions to render different components that has event listeners.

Reducer is getting called thrice for each routing without performing any action

I am trying to integrate redux with react-routing. I found a situation like,
i am accessing the same reducer by two component. i am updating the sate from one component, state is getting updated in store. while routing to the another component,again reducer is getting called automatically and intialized the state with default value.
Here what is happening as per my understanding,reducer is getting called from store and passing the state value as null, so it is taking the default value (feature of ES6) and in same way action.type would null only.
So, My question is why reducer is getting called for every routing even though there is no any user actioned performed. even though if it is calling the reducer, why store is passing null value to the state argument of reducer instead of the state updated by component before routing.
Reducer:
export const userReducer=function(state={name:"rohit",id:123},action){
console.log("user reducer called",state);
switch(action.type){
case "NEW_USER_REG":
console.log("user added");
state=Object.assign({},action.payload);
break;
case "DELETE_USER":
consol.log("user deleted");
break;
}
return state;
}
Component 1(reading and writing from store state):
import React from 'react';
import {Navbar} from '../component/navbar';
import {connect} from 'react-redux'
class Main extends React.Component{
render(){
return(
<div>
<h1>This is main comp.. below is state got from store</h1>
<input type="text" ref="name"/>
<button onClick={()=>this.props.register("rajesh")}>update state</button>
<hr></hr>
{this.props.user.name}
</div>);
}
}
const stateToprops=(state)=>{
return {
user:state.userReducer
}
}
const dispatchToProps=(dispatch)=>{
return{
register:(name)=>{
console.log("fun called ",name);
dispatch({
type:"NEW_USER_REG",
payload:{name:name,id:1}
})
}
}
}
export default connect(stateToprops,dispatchToProps)(Main);
Component 2(reading from store state):
import React from 'react';
import {connect} from 'react-redux';
export class Second extends React.Component{
render(){
return(
<div>
<h1>Hello, This is active component...</h1>
<hr></hr>
{this.props.user.name}
</div>
)
}
}
const stateToProps=(state)=>{
return{
user:state.userReducer
}
}
const dispatchToProps=(dispatch)=>{
return{
adduser:(expense)=>{
dispatch({type:"NEW_USER_REG",payload:expense})
}
}
}
export default connect(stateToProps,dispatchToProps)(Second);
Router Component :
import React from 'react';
import {
BrowserRouter as Router,
Route, Switch
} from 'react-router-dom';
import {Navbar} from '../component/navbar';
import Second from '../component/second';
import Main from '../component/main';
export class App extends React.Component{
render(){
return(
<div>
<div style={{height:80,backgroundColor:'#e8e3e4'}}></div>
<Navbar/>
<div className="text-align: center; margin: auto; width: 60%; padding: 10px;">
<div style={{height:5}}></div>
<div className="container-fluid">
<div className="row">
<div className="col-md-2"> </div>
<div className="col-md-8"style={{height:'auto',backgroundColor:'#e8e3e4'}}>
<Router>
<Switch>
<Route exact path='/' component={Main} />
<Route path='/contact' component={Second}/>
</Switch>
</Router>
</div>
<div className="col-md-2"></div>
</div>
</div>
</div>
</div>
);
}
}
anchor component using not
import React from 'react';
import {Second} from '../component/second';
export class Navbar extends React.Component{
render(){
let styles={width:10};
return(
<div >
<nav className="navbar navbar-inverse" >
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="/">My Learning Project</a>
</div>
<ul className="nav navbar-nav">
<li className="active">Home</li>
<li className="dropdown"><a className="dropdown-toggle" data-toggle="dropdown" href="#">Service<span className="caret"></span></a>
<ul className="dropdown-menu">
<li>Register</li>
<li>Get-Profile</li>
<li>Update</li>
</ul>
</li>
<li>Contact Us</li>
<li>About</li>
</ul>
</div>
</nav>
</div>
);
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route, Switch
} from 'react-router-dom';
import {App} from './app'
import {store} from './store.js'
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('content')
);
Could you please post some snippets of your code like the reducer which is getting called twice and the 2nd component particularly the part where you are dispatching the action. That way we can probably help you.
Solution
OP was using anchor tags <a> to navigate to different urls which were making the page to reload and the redux store to get created again. Switching to <Link> solved the issue.