import images in React - javascript

Here is usually how an image is imported in react
import React, { Component } from "react";
import smallclear from "../images/small/smallClearLaptop.jpeg";
class Images extends Component{
constructor(props) {
super(props);
}
render(){
return(
<div>
<img src={smallclear}></img>
</div>
);
}
}
Instead of directly referring to the image as the name itself I want to use props to build the name using strings so in the render I want to do:
render(){
// this prints smallclear
imgName= this.props.size + this.props.material;
return(
<div>
<img src={imgName}></img>
</div>
);
}
The image is not appearing when I do it the second way. I'm only doing this way because I have to display the image conditionally and that will require a lot of if statements. Is there any way to refer to the imported images without directly naming them in the src?

Related

Problem with loading local images added in object array in react

I made a #JS file called SliderImgs and put an array of objects in that which includes the properties of images of a slider:
const Images=[
{
src:'./files/new-banner-high.jpg',
alt:'banner',
order:'0'
}
]
export default Images
Then I imported this array to a component and then passed that (the array) from props to another component called Slider
import React, { Component } from 'react'
import Images from './SliderImgs'
import Slider from './Slider'
class Body extends Component {
render() {
return (
<div>
<div className="slider">
<Slider pictures={Images}/>
</div>
</div>
)
}
}
export default Body
and finally tried to Print the Image on the screen using the map() method, but I got this error:
Uncaught Error: Cannot find module './files/new-banner-high.jpg'
import React, { Component } from 'react'
class Slider extends Component {
constructor(props){
super(props);
this.state ={
pictures:[]
}
}
static getDerivedStateFromProps(props, state){
return {pictures : props.pictures }
;
}
render() {
return (
<div className="slidercontainer">
{this.state.pictures.map((picture, index)=> {
return(
<img src={require(picture.src)} alt={picture.alt} key={index} />
)
})}
</div>
)
}
}
export default Slider
Normally images should be kept in the public folder.
Move the files directory to the public folder.
Change the array as below.
const Images=[
{
src:'/files/new-banner-high.jpg',
alt:'banner',
order:'0'
}
]
Change the img element like below.
<img src={picture.src} alt={picture.alt} key={index} />

styling SVG paths in React

I am new to React and I'm trying to add an svg image to my component and add dynamic styles to each of its path. However, I am having issues in doing so. I'm using create-react-app
I imported my svg as a React component
import { ReactComponent as SVGimg} from './img/svg-img.svg';
and used it on my render. I was hoping to add styles to all paths by using a for...of loop which I worked on plain HTML/CSS/JS
render() {
const svgImg = document.querySelectorAll('svg path')
for (let path of svgImg) {
path.classList.add('some-class');
}
return(
<div>
<SVGimg/>
</div>
);
}
I also want to mention that the SVG has a lot of paths
You could add a class to the svg say: <svg><path class='pathClass'></svg>
Then in your React component you can get the path by calling: const path = document.getElementsByClassName('pathClass');
And add the class like so: path.classList.add('some-class');
UPDATE
Since you are using a class component you could call the classList.add() method inside the componentDidMont() native React method like so:
class YourComponent extends Component {
constructor(props) {
super(props);
this.svgRef = React.createRef();
}
componentDidMount() {
this.svgRef.current.classList.add('some-class');
}
render() {
return(
<div>
<SVGimg ref={this.svgRef} />
</div>
);
}
}
This will be triggered immediately after the render method finishes.

How do I add javascript code into reactJS file? [duplicate]

This question already has answers here:
Changing style of a button on click
(6 answers)
Closed 3 years ago.
I am very new to reactjs and javascript in general, and I'm trying to figure out how to get this simple js code to work in my reactjs file. I want the text to turn red onClick.
I have tried: Creating an external js file and importing it using Helmet to insert a tag
import React, { Component } from 'react';
import './about.css';
import logo from './S54 Logo 2.svg';
import { Helmet } from "react-helmet";
import aboutJS from './about';
export default class About extends Component {
render() {
return (
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onclick="myFunction()">
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}
this was the js file
export function myFunction() {
document.getElementById("mission-statement").style.color = "red";
}
Ive also tried adding that js code straight into the script tag, instead of importing the file but that didn't work.
I tried putting a tag for that external js file I created into the of my index.html file, and calling the function in my reactjs file.
Nothing is working. Where and how should I add this code?
In JSX, props use this syntax: propName={...} with strings being an exception, where you can do propName="...".
So you should just be able to do onClick={myFunction}
Edit: you might have to do onClick={myFunction.bind(this)} to get your desired effect.
Edit: fixed Camel Case
Zelmi, React uses JSX, which means Javascript XML. You can write JS directly into the component like this:
import React, { Component } from 'react';
import './about.css';
import logo from './S54 Logo 2.svg';
import aboutJS from './about';
export default class About extends Component {
myFunction() {
document.getElementById("mission-statement").style.color = "red";
}
render() {
return (
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onclick="myFunction()">
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}
And thus call the myFunction from anywhere in the page.
You also need to understand how React and the VirtualDOM work, start by reading the docs.
React does not work with the standard html onclick attribute but rather with the React prop onClick, which takes in a function as well, but you need to show React XML that you are calling your JS code by opening a {} code scope like so:
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onClick={this.myFunction}>
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
EDIT
You also unfortunately need to bind your function when using React Class component, in the constructor method:
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.myFunction = this.myFunction.bind(this);
}
Part of the point of React is to abstract away the DOM so you don't have to do things like getElementById and all that.
A simple way to accomplish what you want to do would be something like this:
export default class About extends Component {
constructor(props) {
super(props);
this.state = {
color: "black"
}
}
myFunction = () => {
this.setState({color: "red"});
}
render() {
return (
<div id="about-page">
<img id="about-page-logo-img" src={logo} />
<h2 onClick={this.myFunction} style={{color: this.state.color}}>
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}
Note that if your setup doesn't allow arrow functions in class properties, you may have to bind this to the function like so:
constructor(props) {
super(props);
this.state = {
color: "black"
}
this.myFunction = this.myFunction.bind(this);
}
Zelmi, You can import { myFunction } from 'path/to/your/jsfile.js' which allows you to use myFunction any where in your JS file where your component lives.
Also, use onClick instead of onclick, wrap your function with Carely Braces {} instead of Quotes ""
import React, { Component } from 'react';
import './about.css';
import logo from './S54 Logo 2.svg';
import { myFunction } from 'path/to/your/jsfile.js'; //HERE
import { Helmet } from "react-helmet";
import aboutJS from './about';
export default class About extends Component {
render() {
return (
<div id="about-page">
<Helmet>
<script>
{'aboutJS'};
</script>
</Helmet>
<img id="about-page-logo-img" src={logo} />
<h2 id="mission-statement" onClick={myFunction}>
Catalog the World's Underrepresented Art so everyone can share in the enjoyable experience
</h2>
</div>
)
}
}

Javascript: Error: Cannot find module '../data/icons/table.png'

I'm trying to pass the path of an image to a child component in react and then provide that path as the source attribute in the child component. When I hardcode the path in the child it works, but when I use template literal it does not.
Below is the code snippet. I am unable to understand why the template literal is not working
import React, {Component} from 'react';
class MenuItem extends Component{
render(){
// the below 2 lines print exactly the same thing, i.e., string ../data/icons/table.png
console.log(typeof `${this.props.icon}`, `${this.props.icon}`);
console.log(typeof "../data/icons/table.png", "../data/icons/table.png");
return (
<div className = "sidemenu menu-item">
<img src={require("../data/icons/table.png")} /> //this works
<img src={require(`${this.props.icon}`)} /> //Error: Cannot find module '../data/icons/table.png'.
{this.props.name}
</div>
)
}}
You can load images like modules, if you are using a bundler (like webpack, or yarn) in the same way that API modules.
import React, {Component} from 'react';
import table from './data/icons/table.png';
class MenuItem extends Component{
render(){
return (
<div className = "sidemenu menu-item">
<img src={table} />
</div>
)
}
}

React - Router inside a element using class

How do i render a react component using class?
I have the following code:
class PageLogin extends React.Component {
render() {
return (<p>hello</p>)
}
}
export default PageLogin
When i import it, it render the component entirely, updating the page, so how do i inject it into a div in the component that is rendered?
Ah okay, I think I see what you mean. By default, you can't specify where an individual component is rendered. You tell your main component to render in <div id="id"></div>, so that means EVERY component will use that div as the render root.
However, as of React v16 you can use ReactDOM.createPortal to render a component in any element.
class PageLogin extends React.Component {
render() {
return (
<div>
{ReactDOM.createPortal(<p>hello</p>, document.getElementById('anotherRoot'))}
</div>
)
}
}
export default PageLogin
Ideally though, you'd want to move that code to wherever you are rendering PageLogin:
render() {
return (
<div>
{ReactDOM.createPortal(<PageLogin />, document.getElementById('anotherRoot'))}
</div>
)
}

Categories

Resources