React imported image within a function - reactjs

I want to display dynamically an imported image within a function on React (create-react-app).
Code:
import React, { Component } from 'react';
import reactImg from './img/react.png';
export default class MyPage extends Component {
renderImage(imageName) {
return (
<img src={imageName.toLowerCase()+'Img'} alt={techName} />
);
}
render() {
return (
<p>
{this.renderImage("React")}
</p>
)
}
};
This render:<img src="reactImg" alt="React" />
Instead of what I want: <img src="./img/react.png" alt="React" />
How to display an imported image dynamically within a function please ?

Not sure if it what you are looking for, but here you go:
renderImage(imageName) {
return (
<img src={imageName.toLowerCase()+'Img'} alt={techName} />
^^^^^^^^^ ^^^
// thats wrong concatenation bc your image path looks different
);
}
Try this one instead of your:
<img src={`./img/${imageName.toLowerCase()}.png`} alt={imageName} />

import reactImg from './img/react.png';
import meteorImg from './img/meteor.png';
renderImage(imageName) {
let imageCode;
switch(imageName) {
case 'React':
imageCode = reactImg; break;
case 'Meteor':
imageCode = meteorImg; break;
}
return (
<img src={imageCode} alt={imageName} />
);
};
render(){
return(
<p>
{this.renderImage("React")}
{this.renderImage("Meteor")}
</p>
This render:
<img src="/static/media/react.8d679960.png" alt="React">
It works.

Related

Image not getting displayed when using Reactjs map function. Error--SRC undefined

Here's the error:
Everything else gets displayed well instead of my image. I am using image which saved in my local computer and I'm getting no error in VC editor console. I get error in developer tools console.
./card/index.jsx
import React from 'react'
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.img} alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}
export default Card
./reports/index.jsx
import React from 'react';
import Card from './Card';
import Data from './Card/data';
function createCard(Data){
return <Card
src={Data.src}
alt={Data.alt}
desc={Data.desc}
value={Data.value}
/>
}
const Reports = () => {
return (
<div className="reportsDiv">
{ Data.map(createCard)}
</div>
)
}
export default Reports
data file
import img1 from "./img.jpg";
const Data=[
{
id:1,
img:"{img1}",
alt:"helloworld",
desc:"Sdfasdf",
value:"5GB"
},
{
id:2,
img:{img1},
alt:"helloworld",
desc:"Sd",
value:"35GB"
},
{
id:3,
img:{img1},
alt:"helloworld",
desc:"asdf",
value:"3GB"
}
]
export default Data;
It works if I give value in card component like this:
{/* <Card
img={img1}
alt="helloworld"
desc="System Junk"
value="35GB"
/>
<Card
img={img1}
alt="helloworld"
desc="Sdfasdf"
value="35GB"
/>
<Card
img={img1}
alt="helloworld"
desc="vhghhjghjg"
value="35GB"
/>
*/}
But src is coming undefined if I use map function. Please help. Thanks in advance for help.
Note your createCard function which you're sending src as the image source :
function createCard(Data){
return <Card
src={Data.src}// you're sending src as the prop
alt={Data.alt}
desc={Data.desc}
value={Data.value}
/>
}
But you will use img as the source in the Card component:
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.img} // but using img as the prop which is incorrect
alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}
Change the Card to the bellow will solve the problem:
const Card = (props) => {
console.log(props);
return (
<div className="wrapperDiv">
<img src={props.src} // change it to src
alt={props.alt}/>
<p>{props.desc}</p>
<button>{props.value}</button>
</div>
)
}

Why I can't use an imported component inside a functional component in React?

I am new to React. For the code readability, instead of in-line styled button, I want to write it as a separate class component. I created a customed button 'addImageButton'and imported it to another .js file. It doesn't render the customer button when I try to use it within a functional component. How can I make the functional component be able to use the imported button? Thanks!
//addImageButton.js
import React, { Component } from "react";
class addImageButton extends Component {
render() {
return (
<div>
<button
style={{
borderStyle: "dotted",
borderRadius: 1,
}}
>
<span>Add Image</span>
<span>Optional</span>
</button>
</div>
);
}
}
export default addImageButton;
//AddNewTaskButton.js
import React, { Component } from "react";
import Modal from "react-modal";
**import addImageButton from "../addImageButton";**
class AddNewTaskButton extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
};
this.setShow = this.setShow.bind(this);
this.closeShow = this.closeShow.bind(this);
this.addTaskModal = this.addTaskModal.bind(this);
}
setShow() {
this.setState({
show: true,
});
}
closeShow() {
this.setState({
show: false,
});
}
addTaskModal = () => {
return (
<div>
<Modal
isOpen={this.state.show}
onRequestClose={() => this.closeShow()}
>
**<addImageButton />**
</Modal>
</div>
);
};
render() {
return (
<div>
<button onClick={() => this.setShow()}>
<img src={addIcon} alt={text}></img>;
<span>text</span>
</button>
<this.addTaskModal className="modal" />
</div>
);
}
}
export default AddNewTaskButton;
Easier way would be to just use functional components. Also, react components should be upper case, like so:
export default function AddImageButton() {
return (
<div>...</div>
)
}
create a different component for Modal
import Modal from './Modal'
import AddImageButton from './AddImageButton'
function AddTaskModal() {
return (
<div>
<Modal> <AddImageButton/> </Modal>
</div>
)
}
then
import AddTaskModal from './AddTaskModal'
function AddNewTaskButton() {
return (
<div>
<AddTaskModal/>
</div>
)
}
I don't know your file directories, so I just put randomly.
as for your question, try to make the AddImageButton as a class and see if it renders then. If it doesn't it might be due to something else. Do you get errors? Also maybe create the AddTaskModal class separately and render it out as a component. Maybe that'll help

Props is not showing something on the screen

I am trying to show the number 0 on the screen using props. However nothing shows on the screen and I am not sure why. This is the code:
import React,{Component} from 'react';
import Toolbar from './Toolbar.js';
class Counter extends Component {
constructor(props) {
super(props);
this.state ={
counter:0
}
};
render() {
return(
<div>
{this.state.counter.map(count=>(
<Toolbar count={count}/>
))}
</div>
)
}
};
export default Counter;
And this is where I called it
<div className="toolbar__cart">
<span>{props.count}</span>
<img src="Images/basket.png" alt="Basket" width="40"/></div>
I don't think the map function is applicable here since the value of counter is an integer and not an array. See here for more info on the map function.
If you just want your Toolbar component to display the value of this.state.counter, you could use this:
return(
<Toolbar count={this.state.counter}></Toolbar>
)
And then your Toolbar component would use that counter value like this:
function Toolbar(props) {
return (
<div>
<span>{props.count}</span>
<img src="Images/basket.png" alt="Basket" width="40"/>
</div>
)
}
You are using map function incorrectly.
.map is a function used along with an array
Check out : https://www.w3schools.com/jsref/jsref_map.asp
Correct Code :
render() {
return (
<div>
<Toolbar count={this.state.counter} />
</div>
);
}
You can checkout full code here : https://codesandbox.io/s/naughty-lederberg-hb4wp?file=/src/App.js:203-309
counter.map map function for Arrays - sample
import React,{Component} from 'react';
import Toolbar from './Toolbar.js';
class Counter extends Component {
constructor(props) {
super(props);
this.state ={
counter:[0,1,2]
}
};
render() {
return(
<div>
{this.state.counter.map(count=>(
<Toolbar count={count}/>
))}
</div>
)
}
};

Creating a new room (including inputs and button) and only template shows without the values inside (rcc)

At the button click Create I want to display the room with the content (the new values ​​that holds by the objects in the array - the value I wrote inside the inputs) but fro some reason it's not working and I can't solve it, the problem is that only the template that shows the titles Room and Type are shown without the values inside each of them
Thanks to the helpers!
App.js
import React, { Component } from 'react'
import './App.css';
import Addroom from './components/Addroom.js'
import Room from './components/Room.js'
import 'bootstrap/dist/css/bootstrap.css';
export default class App extends Component {
state={roomsList:[{room:'',type:''}]
}
create=(r,t)=> {
this.setState({roomsList:[...this.state.roomsList,{room:r,type:t}]})
}
render() {
return (
<div>
<h1>My Smart House</h1>
{this.state.roomsList.map((element)=>{
return <Room r={element.room} t={element.type} />
})}
<Addroom add={this.create}/>
</div>
)
}
}
Addroom.js
import React, { Component } from 'react'
export default class Addroom extends Component {
constructor(props) {
super(props)
}
addRoomName=(e)=> {
this.setState({room:e.target.value})
}
addType=(e)=> {
this.setState({type:e.target.value})
}
createRoom=()=> {
this.props.add(this.state.room,this.state.type);
}
render() {
return (
<div>
<input onChange={this.addRoomName} placeholder='Name Your Room'/><br/>
<input onChange={this.addType} placeholder='Whats The Room Type?'/><br/>
<button onClick={this.createRoom}>Create</button>
</div>
)
}
}
Room.js
import React, { Component } from 'react'
export default class Room extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<h1>Room: {this.props.room} </h1>
<h3>Type: {this.props.type} </h3>
</div>
)
}
}
I solved the error, it was a syntax mistake, so what i did, I just asked to get the inside value from my objects in the Room.js components, So it looked like that before:
render() {
return (
<div>
<h1>Room: {this.props.room} </h1>
<h3>Color: {this.props.type} </h3>
</div>
)
}
}
and now I just fixed the syntax to make App.js component understand that I want to display the values inside the objects when I'm creating a new room with my button, because now r and t are represent the values of the variables..
render() {
return (
<div>
<h1>Room: {this.props.r} </h1>
<h3>Color: {this.props.t} </h3>
</div>
)
}
}
This is a very small mistake that is easy to understand, so it is always important to go through your code slowly and safely! Hope it will help some f.e devs in the future..

Using Link component dynamically in React-Router

Depending on a conditional stored in component state, I would like a particular component being rendered to either be wrapped in a Link tag or a regular div tag (or no tag works just as well!)
What I'm currently doing seems verbose and redudnant; I feel like there's a shorter way I could write this component to keep my code DRY.
Both variables storing my linkThumbnail and defaultThumbnnail components are pretty much exactly the same, except for the fact that one of them is contained within a Link component.
I then use a ternary operator in the return statement to give me the desired component.
Here's some pseudocode as an example:
import React, { Component } from "react";
import { Link } from "react-router-dom";
class ExampleComponent extends Component {
state = {
renderLink: false
};
render() {
const linkThumbnail = (
<Link
to={{
pathname: `/someMovieId`,
state: 'some-data'
}}
>
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
</Link>
);
const defaultThumbnail = (
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
);
//here I use a ternary operator to show the correct component...shorter method of doing this?
return this.state.renderLink ? linkThumbnail : defaultThumbnail;
}
}
export default ExampleComponent;
Try creating another component which gets this.state.renderLink as a prop:
const ThumbnailLink = ({enabled, children, ...props}) => {
if (enabled) {
return <Link {...props}>{children}</Link>;
} else {
return <div>{children}</div>;
}
}
class ExampleComponent extends Component {
render() {
return (<ThumbnailLink enabled={this.state.renderLink} to={{pathname: `/someMovieId`, state: 'some-data'}}>
<div>
<div className='movie' onClick={this.getMoviePreview}>
<img
src={
poster
? `https://image.tmdb.org/t/p/w300${poster}`
: "https://via.placeholder.com/300"
}
alt='something here'
/>
</div>
</div>
</ThumbnailLink>);
}
}

Resources