Ads Top

how to call an image in the react?

How to use images in the react?
First of all, we need to wrap src with Curly Brackets as src={} and then define a variable and then import variable name where you want to use an image as given example below:
1. import logo from './logo.svg'; <img src={logo} alt="Logo" width="100" /> import imggss from '../../images/footer-facebook.png';
<img src={imggss} alt="Facebook" />

you will import this line at the starting of the Component and then you will use an image tag where you will render your code.

2. Also, you can use image with "require" directally as <img src={require('./logo.svg')} alt="Logo" width="200" /> but with require.

3. And if you want to use image dynamically in react then it needs to use "require.context" as a given example.
var images = require.context('../../images');

socialFIcon:[
{img:'./footer-facebook.png', alt:'Facebook', titt:'Facebook', href:'facebook.com'},{img:'./footer-twitter.png', alt:'Twitter', titt:'Twitter', href:'twitter.com'},
img:'./footer-youtube.png', alt:'Youtube', titt:'Youtube', href:'youtube.com'}
]
rendersocialFIcon = () => {
return this.state.socialFIcon.map(item => <Navlinks mySrc={images(item.img)} myAlt={item.alt} myTitle={item.titt} linkss={item.href} />)
}
<ul> {this.rendersocialFIcon()}</ul>

You will find the result as a given screenshot.



4. Another way to call an image dynamically at for the whole page, need to define one base URL as below:
const images = require.context('../../assets/images')
<img src={images('./yourimage.png')} alt="Image alt" />

5. If you need call any image in the background with CSS then need to use folder structure and maintain the path of your images as:
.mainBannerBg { backgroundurl(../src/assets/images/mainBannerBg.pngrepeat-x center bottom;

6. If you have any absolute path or any live path then you can use images in the public folder as given below code:


const images = [
'images/mytest1.png','images/mytest2.png',
  '//https://www.anythinglearn.com/anyimage.png',
  '//https://www.anythinglearn.com/anyimage.png',
  '//https://www.anythinglearn.com/anyimage.png',
];






1 comment:

Copyright Reserved to Anything Learn. Powered by Blogger.