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.
Related
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
I'm trying to add a custom HTML attribute on a React component:
const Parent = () => (
<div className="parent">
<Child data-custom="foo" />
</div>
);
Where Child is another React component, but the attribute gets stripped on the output HTML. I'm aware that I could simply add the attribute on the Child root element, like so:
const Child = () => <div className="child" data-custom="foo" />
Or read the attribute in the Child component via props, but that's not what i'm looking since that would couple the attribute with the component, and I'm looking for a more contextual approach (the attribute would be used for test automation purposes).
Is there a clean way to do that in React?
I'm also considering writing a Babel plugin to add the attribute or prevent the stripping, but that would be another question.
Thanks!
React element doesn't necessarily correspond to DOM element that could have HTML attributes. React component can be rendered to multiple DOM elements or no elements at all.
If Child should be able to provide additional props or attributes to child DOM element, it should pass them explicitly:
const Child = props => <div className="child" {...props} />
This way data-custom="foo" will be passed to <div>.
For this, you can try this in your react script.
const MyCompo = () => {
return (
<div>
<p>HTML Code</p>
</div>
);
}
export default About;
Otherwise you can create class and then define your components and then export them.
import React from 'react';
import '../assets/css/style.css';
import '../assets/css/pure-min.css';
import '../assets/css/custom.css';
import 'font-awesome/css/font-awesome.min.css';
import $ from 'jquery';
class FirstScreen extends React.Component {
constructor(props) {
super(props);
this.handleLoad = this.handleLoad.bind(this);
}
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
handleLoad() {
}
render() {
return <div>HTML Code</div>;
}
}
export default FirstScreen;
You could use the below syntax
const Parent = () => (
<div className="parent">
<Child data-custom="foo"/>
</div>
);
const Child = ({...props}) => (<div className="child" {...props} />)
I am running into an issue that seems to be "similar" to other issues dealing with a JSON object in React, though I can not seem how to translate these answers. I am creating a small game inside of React (not React Native). I am able to call my JSON object and pull text, though, when it comes to pulling an image path, it will not render. To get a basic idea of this game (that was in HTML/ JS) take a look at this link for the overall functionality.
Here is the Issue, I have a dynamically rendering set of objects based on state in the parent Component (GameLogic.js). I am then passing state down to the great-great-grandchild elements where it will render a two photos. These photo paths are stored in a local JSON file (I can read strings from the characters.json file in a console.log at this level). Though it can read the path (via console.log), it is not rendering these images. I am how ever able to render these images as long as I am not stringing together a long dynamic path.
Here is the file structure:
-components folder
|-GameLogic.js (parent element that handles the render)
|-Bandersnatch.js (child element)
|-NewComponents folder
|-ImageContainer.js (grandChild element)
|-ImageSquare.js (great grandChild element)
-images folder
|-snatch_images folder (yes... I know how bad this sounds...)
|-escape_snatch.png
|-The rest of the images (there are about 20)
-characters.json
-App.js
JSON example: I need the file path at Array[0].scene[0].choiceOneImg
[
{
"name": "Giraffe",
"alive": true,
"active": true,
"staticImg": "images/characters/static/static_giraffe.png",
"animatedImg": "images/characters/animated/animated_giraffe.png",
"cagedImg": "images/characters/caged/caged_giraffe.png",
"scene": [
{
"used": false,
"backgroundImg": "images/BG_images/zooBG.png",
"question": "........." ,
"answerTrue": ".......",
"answerFalse": ".......",
"choiceOne": "RUN FOR IT!",
"choiceTwo": "Stay loyal",
"choiceOneImg": "../images/snatch_images/escape_snatch.png",
"choiceTwoImg": "images/snatch_images/stay_snatch.png",
"incorrectResult": 0,
"correctAnswer": "choiceOne",
"correct": true
},
Here is the Parent, GameLogic.js that passes the currentCharacter, sceneLocation from the state that is constantly changing:
import React, { Component } from "react";
import Snatch from "./Bandersnatch";
import characters from "../characters.json";
class GameLogic extends Component {
state ={
unlockedCharacters : 0,
currentCharacter : 0,
sceneLocation : 0,
points : 0,
showCaracterSelect: true,
showMessage: false,
showSnatch: false,
showCanvas: false,
}
componentDidMount() {
}
render() {
return (
<Snatch
sceneLocation = {this.state.sceneLocation}
currentCharacter = {this.state.currentCharacter}
choiceOneAlt = "ChoiceOne"
choiceOneImg = {characters[this.state.currentCharacter].scene[this.state.sceneLocation].choiceOneImg}
choiceTwoAlt = "ChoiceTwo"
choiceTwoImg = {characters[this.state.currentCharacter].scene[this.state.sceneLocation].choiceTwoImg}
/>
)
}
}
export default GameLogic;
Then this is passed to the child component, Bandersnatch.js:
import React, { Component } from "react";
import characters from "../characters.json";
import { HeaderH2, ImageContainer, ImageSquare, ImageText, ProgressBar, Timer } from "./NewComponents/AllComponents";
const Snatch = (props) => {
return (
<>
<title>Decision Time</title>
<div className="w3-container">
<div className="container">
<HeaderH2 text="What Would You Like To Do?" />
<div className="row">
<ImageContainer
sceneLocation = {props.sceneLocation}
currentCharacter = {props.currentCharacter}
choiceOneAlt = {props.choiceOneAlt}
choiceOneImg = {props.choiceOneImg}
choiceTwoAlt = {props.choiceTwoAlt}
choiceTwoImg = {props.choiceTwoImg}
/>
{/* <ProgressBar /> */}
{/* <ImageText
sceneLocation = {props.sceneLocation}
currentCharacter = {props.currentCharacter}
/> */}
</div>
</div>
</div>
</>
);
}
export default Snatch;
Which is then passed to ImageContainer:
import React, { Component } from "react";
import ImageSquare from "./ImageSquare";
import characterObject from "../../characters.json";
const ImageContainer = (props) => {
return (
<>
<div className="col-md-6 optionOneclassName">
<ImageSquare
imgsrc={props.choiceOneImg}
altText={props.choiceOneAlt}
/>
</div>
<div className="col-md-6 optionTwoclassName">
<ImageSquare
imgsrc={props.choiceTwoImg}
altText={props.choiceTwoAlt}
/>
</div>
</>
)
};
export default ImageContainer;
And then finally accepted in the ImageSquare.js:
import React from "react";
const ImageSquare = (props) => { // passing in the img src
return (
<img src={props.imgsrc} alt={props.altText} height="600" width="600" />
)
};
export default ImageSquare;
Thank you so much for your help! I am not sure if it is easier, but the repo is here
Use require to load the image. Passing path to img directly won’t work. Either you need import or require to load the image
You need to add ../ before path
Change
import React from "react";
const ImageSquare = (props) => { // passing in the img src
return (
<img src={props.imgsrc} alt={props.altText} height="600" width="600" />
)
};
export default ImageSquare;
To
import React from "react";
const ImageSquare = (props) => { // passing in the img src
const path = "../"+props.imgsrc;
return (
<img src={require(path)} alt={props.altText} height="600" width="600" />
)
};
export default ImageSquare;
I'm retrieving images from the database in REACT and have created a holder for an image with thumbnails at the bottom.
I would like to know how I can make the interface behave like eCom sites, whereupon clicking the thumbnail, its respective image is loaded in the bigger area.
Below is the REACT code.
import React from "react";
import { Link } from "react-router-dom";
import ImageList from "../ImageList";
const ProductDetails = props => {
const images = require.context(
"../../../strapui/app/public/uploads",
true,
/\.jpg$/
);
const keys = images.keys();
const svgsArray = keys.map(key => images(key));
return(
<div className="desContainer ">
<div className="desimgContainer ">
<ImageList
styles="heroImage"
imagePath={props.selectedItem[0].image[0]}
svgsArray={svgsArray}
/>
</div>
<div className="thumbs">
<ImageList
styles="thumbnail"
imagePath={props.selectedItem[0].image[0]}
svgsArray={svgsArray}
/>
</div>
<div className="thumbs">
<ImageList
styles="thumbnail"
imagePath={props.selectedItem[0].image[1]}
svgsArray={svgsArray}
/>
</div>
<div className="thumbs">
<ImageList
styles="thumbnail"
imagePath={props.selectedItem[0].image[2]}
svgsArray={svgsArray}
/>
</div>
</div>
);
};
export default ProductDetails;
The images are pulled from the database using the following code
import React from "react";
const ImageList = props => {
if (
props.imagePath === undefined ||
props.imagePath === null ||
props.imagePath.length === 0
)
return null;
const path = props.svgsArray.find(
str => str.indexOf(props.imagePath.hash) > 1
);
return <img src={path} alt={props.imagePath.hash} className={props.styles} />;
};
export default ImageList;
I was wondering if I could use a switch case to show the image when a thumbnail is clicked?
will it work? if it will, can you pls direct me how?
Use onClick event and attach it with some function which should do some code magic.
for e.g:
largeSizeImage () {
/* some code logic */
}
return (
<div className="thumbs" onClick={largeSizeImage()}>
<ImageList
styles="thumbnail"
imagePath={props.selectedItem[0].image[1]}
svgsArray={svgsArray}
/>
</div>
)
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.