I'm new to React, and I'm sorry beforehand if I use the wrong terms for certain pieces!
I have imported some images in the top if my file with import face_1 from "./assets/face-1.png"; (where the numbers increase up to 6, since I'm making dice)
Later on, I want to show those images based on the value of the die, so I want to grab the images as follows: <img className="dice-image" src={face_#} alt={roll} />;. I want # to be the same value as {roll}, but I can't figure out how I can add the value of {roll} to src?
So basically, I want the <img>-tag to look like this:
<img className="dice-image" src={face_{roll}} alt={roll} />
Is this at all possible? Or do I have to create the face_3 just before I call it as a prop?
Putting all the values into an array, as suggested by Guy Incognito, is a straightforward way to handle this:
const faces = [face_1, face_2, face_3, face_4, face_5, face_6];
return (
<>
{faces.map((face, i) => (
<img className="dice-iamge" key={i} src={face} alt={roll} />
))}
</>
);
Related
I'm using jsplumbtoolkit-react 2.x version. Using toolkit.addNode to add new nodes dynamically to the graph. But I'm struggling to draw the connection between the newly added nodes. Can someone please point me to the right documentation or if there is any example that I can follow for this specific version?
I added the following properties on the node component
jtk-port={ctx.data.id}
jtk-scope="varchar"
jtk-source="true"
jtk-target="true"
I do have elementsDraggable: true, so all I'm able to do is drag the node but not form a connection. I tried using addPort but with no luck and the jsPlumbtoolkit documentation has not helped so far.
It's possible you are looking at the 5.x documentation, given that you're using attributes in the above example, although I should note that for users of 5.x the attributes are prefixed with data-, eg data-jtk-source="true" etc. In 2.x this connectivity is not configured with attributes, though, but with elements. For instance, for this demonstration:
https://demo.jsplumbtoolkit.com/react-flowchart-builder/
This is the render method for the action component:
render() {
const obj = this.node.data;
return <div style={{width:obj.w + 'px', height:obj.h + 'px'}} className="flowchart-object flowchart-action">
<div style={{position:'relative'}}>
<svg width={obj.w} height={obj.h}>
<rect x={10} y={10} width={obj.w-20} height={obj.h-20} className="inner"/>
<text textAnchor="middle" x={obj.w/2} y={obj.h/2} dominantBaseline="central">{obj.text}</text>
</svg>
</div>
<div className="node-edit node-action" onClick={this.edit.bind(this)}></div>
<div className="node-delete node-action delete" onClick={this.remove.bind(this)}></div>
<div className="drag-start connect"></div>
<jtk-target port-type="target"/>
<jtk-source port-type="source" filter=".connect"/>
</div>
}
The complete source for the version 2.x code for that demonstration is here:
https://github.com/jsplumb-toolkit-demonstrations/react-flowchart-builder/blob/2.x/src/action-component.jsx
I am working on importing game covers from an API response based on a search and displaying them on a page.
At this point, I am able to retrieve the data for the title of the game, and the url for the image of the cover that I need. However, I am running into an error regarding the url of the game cover.
TypeError: Cannot read properties of undefined (reading 'url')
This points to this line of code
const gameData = result.map((game) => ({
gameId: game.id,
name: game.name,
---> cover: game.cover.url, <--- this line
}));
setSearchedGames(gameData);
My api response looks like this:
From what I can tell, the API is providing the url and I'm unsure of why it's causing a problem. If I remove that line of code, everything runs as normal, and the results display without covers. With that line of code in, gameData returns undefined entirely. Thank you in advance for any assistance and I'd be happy to add any additional code that may help.
This is an easy fix, when react first renders there isn't a value and obviously there's no conditions to catch this...yet
there is syntax that will allow you to do a check with minimal coding
example: {return data.game.url}
fixed: {return data?.game?.url}
just adding this simple question mark after data?. you are checking if the data has returned undefined, void or pending. You can also use this one:
example: {data && data.game.url}
Seems like you're accessing the key cover that doesn't always exists in the returned response. You'd need to check if that key exists before accessing it or use optional chaining like so game?.cover?.url
More info on optional chaining:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
It looks like there is no problem within your attached code snippet.
I think you need to check above of your code snippet.
Maybe there is a area that modify gameData or something.
Please double check it.
Thank you for your responses. I was able to solve the problem with the following:
I altered the code snippet from above to match this:
const gameData = result.map((game) => ({
gameId: game.id,
name: game.name,
---> cover: game.cover, <--- removed .url
}));
setSearchedGames(gameData);
My original return statement had set up the cards to be structured like so:
<Card key={game.gameId} border='dark'>
{game.cover ? (
<Card.Img src={'http:' + game.cover} alt={`The cover for ${game.name}`} variant='top' />
) : null}
<Card.Body>
<Card.Title>{game.name}</Card.Title>
</Card.Body>
</Card>
I changed that to this:
<Card key={game.gameId} border='dark'>
{game.cover ? (
---> add .url here <Card.Img src={'http:' + game.cover.url} alt={`The cover for ${game.name}`} variant='top' />
) : null}
<Card.Body>
<Card.Title>{game.name}</Card.Title>
</Card.Body>
</Card>
I am having trouble to have a map within a map.
As you can see below I have commented several tries, ideally I wanted to use workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>)
directly.
If I use it directly I will have "Cannot read properties of undefined (reading 'map')".
On this version I will get a undefined is not iterable (cannot read property Symbol(Symbol.iterator)) even though console.log seems to work fine and shows the type as Array as expected. The Array.from is useless but I since I am not understanding what's happening I gave it a try.
const work = this.props.data.work.map( workItem => {
console.log(workItem.bullets);
//let bulletPts = workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>);
//let bps = workItem.bullets.map((bulletItem, i)=>"toto");
let array = Array.from(workItem.bullets);
return (
<div key={workItem.company}>
<h3>{workItem.company}</h3>
<p className="info">
{workItem.title}
<span>•</span> <em className="date">{workItem.years}</em>
</p>
<p>{workItem.description}</p>
<ul>
{
array.map(bulletItem => "test")
}
</ul>
</div>
);
});
I also took a look at How to map inside a map function in reactjs as it looked like a similar problem but I was not able to apply it to my issue.
I don't think it is needed but If you want to see the full project I am trying to add bullet points for resume, resumeData.json needs to be modified to contain some bulletPoints.
https://github.com/nordicgiant2/react-nice-resume
There is somethign wrong with your JSON :D
I'm looking to purify HTML with the HtmlPurifier package and add attributes to certain elements. Specifically, I'd like to add classes to <div> and <p> elements so that this:
<div>
<p>
Hello
</p>
</div>
Gets purified/transformed into this:
<div class="div-class">
<p class="p-class">
Hello
</p>
</div>
How would one go about doing this with HtmlPurifier? Is it possible?
I believe you could do this by doing something along these lines (though please treat this as pseudocode, the last time this scenario worked for me was years ago):
class HTMLPurifier_AttrTransform_DivClass extends HTMLPurifier_AttrTransform
{
public function transform($attr, $config, $context) {
$attr['class'] = 'div-class';
return $attr;
}
}
class HTMLPurifier_AttrTransform_ParaClass extends HTMLPurifier_AttrTransform
{
public function transform($attr, $config, $context) {
$attr['class'] = 'p-class';
return $attr;
}
}
$htmlDef = $this->configuration->getHTMLDefinition(true);
$div = $htmlDef->addBlankElement('div');
$div->attr_transform_post[] = new HTMLPurifier_AttrTransform_DivClass();
$para = $htmlDef->addBlankElement('p');
$para->attr_transform_post[] = new HTMLPurifier_AttrTransform_ParaClass();
Remember to allowlist the class attribute for div and p as well, if you haven't already.
That said, at first glance, HTML Purifier doesn't seem to be the right place for this kind of logic, since adding class names isn't relevant for the security of your site (or is it?). If you're already using HTML Purifier to allowlist your HTML tags, attributes and values, and just want to leverage its HTML-parsing capabilities for some light-weight additional DOM manipulation, I see no particular reason not to. :) But it might be worth reflecting on whether you want to add the classes using some other process (e.g. in the frontend, if that's relevant for your use case).
Trying to add an image from my assets folder, but can't seem to reach back that far?
<img class='fade-in' src={'.../assets/images/logos/SWSLogoNOBG.png'} />
Can I not reach back that far with the dots? I can use two and it works, but is three too much?
I've also tried
import SWSLogo from '.../assets/images/logos/SWSLogoNOBG.png';
then done
<img class='fade-in' src={SWSLogo}/>
but that also doesn't work?
I feel super dumb and could use some help cause this one little problem has taken me two days of trying and I've made zero progress.
Edit:
I've made it work, but only by moving my image file into the same folder as my Home.js file.
Can react not reach files outside of the immediate directory? Why is this so stupid?
If you need to go multiple nested folders up then for every folder you need another '../'
for example, if you have
1. src
2. folder
3. folder
index.js
app.js
you would need to do '../../app.js'
if you are using a hard coded path, use quotes:
<img
alt="dolphin"
src="../../images/dolphin.jpg"
ariaLabel="dolphin"
/>
if you are pulling from say a JSON you would do something like:
const animals = {
dolphin: {
image: '../../images/dolphin.jpg',
facts: ['Dolphins have been shown to give distinct names to each other!', 'Dolphins are known to display their own culture!', 'Dolphins have two stomachs!']
},
lobster: {
image: '../../images/lobster.jpg',
facts: ['Lobsters taste with their legs!', 'Lobsters chew with their stomachs!', 'Lobsters can live as long as 100 years.']
},
starfish: {
image: '../../images/starfish.jpg',
facts: ['Starfish can have up to 40 arms!', 'Starfish have no brain and no blood!', 'Starfish can regenerate their own arms!']
}
};
const images = [];
for (const animal in animals) {
images.push (
<img
alt={animal}
src={animals[animal].image}
ariaLabel={animal}
/>
)
};
const allImages =
(
<div className='animals'>
{images}
</div>
)
ReactDOM.render(allImages , document.getElementById('root'));