Placing logo image into navbar - reactjs

I am getting a broken image when I put my logo inside of the navbar. I have it saved locally inside the public folder.
I have tried passing as a prop, and directly linking to the path, but i cannot seem to get it to work.
import AppBar from '#material-ui/core/AppBar'
import Toolbar from '#material-ui/core/Toolbar'
import Typography from '#material-ui/core/Typography'
const NavBar = () => {
return(
<div>
<AppBar className='nav-bar' position="static" color='white'>
<Toolbar>
<Typography variant="title" >
<img src='../../public/LQ_Logo.png' width={182} height={64} />
</Typography>
</Toolbar>
</AppBar>
</div>
)
};
export default NavBar;
I need the logo to be displayed in the left corner of the navbar

For img within Public folder use relative path to Public.
For public/Vector.png use ./Vector.png.
Moreover, if it's a SVG you can import it as ReactComponent, for example:
import { ReactComponent as CatImg } from "./add-debug.svg";
const NavBar = () => {
return (
<div>
<AppBar className="nav-bar" position="static" color="white">
<Toolbar>
<Typography variant="title">
<CatImg height={100} />
</Typography>
</Toolbar>
<Toolbar>
<Typography variant="title">
<img src="./Vector.png" alt="bug" height={100} />
</Typography>
</Toolbar>
</AppBar>
</div>
);
};
Demo:

Did you check that relative path is correct? Maybe something is missing in "../../public/LQ_Logo.png".
You can try to use this alternative:
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
Change the png image to svg (is better to escalate width/heigh for web), and then import the image as a component and call the component in your code.

Related

Image is not displayed for avatar in browser - using Material UI

I am newbie and trying to get hands-on working on a project. I have referred to the other questions but they are not similar to this. I am unsure what I am missing here.
I have imported the image in Component-1 and sending it as props to Component-2
here is my code
**Component-1**
import HomeIcon from '#mui/icons-material/Home';
import HeaderOption from './HeaderOption';
import avatar from '../src/images/avatar.jpg';`enter code here`
function Header() {
return (
<div className='right_header'>
<HeaderOption Icon={HomeIcon} title='Home' />
<HeaderOption avatarIcon={avatar} title='Me' />
</div>
);
}
export default Header;
**component-2**
import React from 'react';
import './HeaderOption.css';
import AccountCircleIcon from '#mui/icons-material/AccountCircle';
function HeaderOption({ avatarIcon, Icon, title }) {
return (
<div className='headerOption'>
{Icon && <Icon className='headerOption_icon' />}
{avatarIcon && (
<AccountCircleIcon className='headerOption_icon' src={avatarIcon} />
)}
<h3 className='headerOption_title'>{title}</h3>
</div>
);
}
export default HeaderOption;
I assume what you need is this:
import * as React from 'react';
import Avatar from '#mui/material/Avatar';
import Stack from '#mui/material/Stack';
export default function ImageAvatars() {
return (
<Stack direction="row" spacing={2}>
<Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" />
<Avatar alt="Travis Howard" src="/static/images/avatar/2.jpg" />
<Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" />
</Stack>
);
}
AccountCircleIcon is an icon and you can't change that. Therefore what you should do is this:
avatarIcon && <Avatar alt="Cindy Baker" className='headerOption_icon' src={avatarIcon} /> )}

react movie app breaking when navigating movie detail page

i am creating a react movie app that uses an movie app API from rapid API. on home page everything is working perfectly and I am able to render all movies in the form of cards. i have set the app in such a way that when user clicks on movie card it should direct to Moviedetail page. for this i am using react-router-dom and everything is set up right. on clicking movie card it does navigate to Moviedetail page but nothing is being rendered and getting this error in browser console.
(Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at Details (Details.js:18:1));
but if i comment Detail and MovieTrailers component in MovieDetails page and uncomment it then everything on MovieDetails page is rendered perfectly. again if i refresh the page it breaks again and i get the same browser console error.
import React, {useState, useEffect} from "react";
import {Box} from "#mui/material";
import {useParams} from "react-router-dom";
import MovieTrailers from "../components/MovieTrailers";
import Details from "../components/Details";
import {fetchData, options} from "../utils/fetchData";
function MovieDetails() {
const [movieDetailData, setMovieDetailData] = useState({});
const [movieTrailerData, setMovieTrailerData] = useState([]);
const {id} = useParams();
// console.log(id);
console.log(movieDetailData);
console.log(movieTrailerData);
useEffect(()=>{
const fetchMovieData = async ()=> {
const detailData = await fetchData(`https://movies-app1.p.rapidapi.com/api/movie/${id}`, options);
setMovieDetailData(detailData.result);
const trailerData = await fetchData(`https://movies-app1.p.rapidapi.com/api/trailers/${id}`, options);
setMovieTrailerData(trailerData.result);
}
fetchMovieData();
},[id]);
return(
<Box>
<Details
movieDetailData={movieDetailData}
/>
<MovieTrailers
movieTrailerData={movieTrailerData}
/>
</Box>)
}
export default MovieDetails;
////here is Details component
import React from "react";
import {Box, Stack, Typography, Chip} from "#mui/material";
function Details(props) {
const{image, titleOriginal, countries, genres, rating, release, description} = props.movieDetailData;
return <Stack direction="row" width="100%" sx={{backgroundColor:"#fff"}}>
<img className="movie-poster" src={image} alt="movie-poster"/>
<Stack p="50px" sx={{width:"60%"}}>
<Typography variant="h2" fontWeight="700">
{titleOriginal}
</Typography>
<Box pt="30px" sx={{display:"flex", gap:"30px"}}>
<Chip label={<Typography variant="h6" fontWeight="700">{`rating : ${rating}`}</Typography>} />
<Chip label={<Typography variant="h6" fontWeight="700">{`release: ${release}`}</Typography>} />
</Box>
<Typography variant="h6" pt="30px">
{description.length>600 ? description.substring(0, 601) : description}
</Typography>
<Box pt="30px" sx={{display:"flex", gap:"30px"}}>
<Chip label={<Typography variant="h6" fontWeight="700">{`genre : ${genres[0].name}`}</Typography>} />
<Chip label={<Typography variant="h6" fontWeight="700">{`origin : ${countries[0].name}`}</Typography>} />
</Box>
</Stack>
</Stack>
}
export default Details;
////here is MovieTrailer component
import React from "react";
import {Box, Stack, Typography} from "#mui/material";
import TrailerCard from "./TrailerCard";
import {nanoid} from "nanoid";
function MovieTrailers({movieTrailerData}) {
console.log(movieTrailerData);
return <Box p="30px">
<Typography variant="h4" pt="40px" pb="50px" fontWeight="700" m="auto">{`Watch ${movieTrailerData[0].title}`}
</Typography>
<Stack direction="row" justifyContent="space-between">
{(movieTrailerData.slice(0, 3)).map((trailer)=>(
<TrailerCard trailer={trailer}/>
))}
</Stack>
</Box>
}
export default MovieTrailers;
////here is TrailerCard component
import React from "react";
import {Box, Stack, Typography, Chip} from "#mui/material";
function TrailerCard({trailer}) {
const{thumbnail, ago, author, views, title, url, description} = trailer;
return <Box className="trailer-card" p="10px" backgroundColor="#fff" width="25%">
<Stack>
<a
className="movie-trailer-link"
href={url}
target="_blank"
rel="noreferrer">
<img className="movie-trailer-thumbnail" src={thumbnail} alt="movie-trailer"/>
<Typography pt="10px" variant="body1" fontWeight="700" >
{title}
</Typography>
<Stack paddingBlock="10px" direction="row" justifyContent="space-between" gap="10px" flexWrap="wrap">
<Chip label={`views: ${views}`} />
<Chip label={`ago: ${ago}`}/>
</Stack>
<Typography variant="subtitle2">{`YT: ${author.name}`}</Typography>
<Typography variant="body2" pb="20px">
{description}
</Typography>
</a>
</Stack>
</Box>
}
export default TrailerCard;
In your movie detail component, add a loading state initially set to true. Upon resolution of the API call in the useEffect, set the loading variable to false.
In the jsx, render the page data if loading is false else show a loader or something else
movieDetailData is an empty object before you fetch your data from backend. That's why you get an error.
First check if your props has suitable keys.
import React from "react";
import {Box, Stack, Typography, Chip} from "#mui/material";
function Details(props) {
if (Object.keys(props.movieDetailData).length == 0)
return null;
const{image, titleOriginal, countries, genres, rating, release, description} = props.movieDetailData;
// rest of your code
}

Dynamic data are not rendering on the browser

Good day, I'm trying to create a MEARN stack application with react-redux. I am already able to post data to my MongoDB atlas, and I am also able to fetch the data and console.log it. But when I try to render the data to my front end the browser returns an empty page. I would like to know what is causing this issue. This is my first time creating a react application.
import './Experience.css';
import Post from './Posts/Post';
import { Grid, CircularProgress } from '#material-ui/core';
import { useSelector } from 'react-redux';
function Experience() {
const posts = useSelector((state) => state.posts);
console.log(posts); //Logged my data on DevTool -> Console (see image below)
return (
!posts.length ? <CircularProgress /> : (
<Grid container alignItems="stretch" spacing={3}>
Test //view browser
{posts.map((post) => (
<Grid key={post._id} item xs={3} >
<Post post={post} />
</Grid>
))}
</Grid>
)
);
}
export default Experience;
import React from 'react';
import { Card, CardActions, CardContent, CardMedia, IconButton, Typography, CardHeader, Avatar } from '#material-ui/core';
import MoreVertIcon from '#material-ui/icons/MoreVert';
const Post = ({ post }) => {
return (
<Card>
<CardMedia image={post.companyLogo} />
<CardHeader
avatar={
<Avatar aria-label="recipe">
<img href={post.employerImage}/>
</Avatar>
}
action={
<IconButton aria-label="settings">
<MoreVertIcon />
</IconButton>
}
title={post.employerName}
subheader={post.jobTitle}
/>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">{post.responsibility.map((tag) => `🖱️${tag} `)}</Typography>
</CardContent>
<CardActions>
<Typography variant="body2" color="textSecondary" component="p">{post.employedDate}</Typography>
</CardActions>
</Card>
);
}
export default Post;
Since you are getting response from the db, there must be a rendering error.
From a quick look I see that you have missused the Avatar component.
It should be like: <Avatar alt="recipe" src={post.employerImage} />
or if you want to utilize the children prop, img tag takes src not href:
<Avatar aria-label="recipe">
<img src={post.employerImage}/>
</Avatar>

Can't include React UI frameworks (Grommet)

I have problems importing UI libraries, I had problem with ant design library so I decided to try different one, now I have problem importing Grommet.
What am I doing wrong? I added dependencies according documentation and added examples included in documentation yet still not working.
I am trying to execute this code from documentation
But it doesn't look the same at all
I work with codesandbox.io, here is link for the code on it
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Heading from "grommet/components/Heading";
import Box from "grommet/components/Box";
import Header from "grommet/components/Header";
import Title from "grommet/components/Title";
import Search from "grommet/components/Search";
import Menu from "grommet/components/Menu";
import Anchor from "grommet/components/Anchor";
import "grommet-css";
class HelloWorldApp extends React.Component {
render() {
return (
<div>
<Header>
<Title>Sample Title</Title>
<Box flex={true} justify="end" direction="row" responsive={false}>
<Search
inline={true}
fill={true}
size="medium"
placeHolder="Search"
dropAlign={{right: "right"}}
/>
<Menu dropAlign={{right: "right"}}>
<Anchor href="#" className="active">
First
</Anchor>
<Anchor href="#">Second</Anchor>
<Anchor href="#">Third</Anchor>
</Menu>
</Box>
</Header>
<Box>
<Heading>
Hello, I'm a Grommet Component styled with
grommet-css
</Heading>
</Box>
</div>
);
}
}
var element = document.getElementById("root");
ReactDOM.render(<HelloWorldApp />, element);
So according to your code:
<Menu dropAlign={{right: "right"}}>
was missing the icon attribute, without which the Menu component directly renders the Anchor, the menu-items component.
add import for the icon of your choosing, i.e: Actions ( from the example )
import Actions from 'grommet/components/icons/base/Actions';
add the icon attribute to the Menu component:
<Menu
icon={<Actions />}
dropAlign={{ right: 'right' }}
>
<Anchor href="#" className="active">First</Anchor>
<Anchor href="#">Second</Anchor>
<Anchor href="#">Third</Anchor>
</Menu>
here's a codesandbox.io link which fixes your issue:
https://codesandbox.io/s/237xo7y48p

Insert image into Material-UI AppBar

I've been looking for a way to insert a plain image file into the AppBar of Material-UI on the official docs but it seems like the only non-text things you can put in the AppBar are either text icons or SVG icons. Is there a way to display actual images in the AppBar?
There are several options to insert a background image for Material-UI AppBar.
Here is one that I prefer:
Import the image:
import headerBackground from "../../Assets/headerBackground.png";
Add the image to the stylesheet as follow:
header: {
backgroundImage: `url(${headerBackground})`,
},
Set the class component:
const classes = useStyles();
return (
<>
<AppBar className={classes.header}> ... </AppBar>
Here is a complete example:
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import { AppBar, Toolbar, Typography } from "#material-ui/core";
import headerBackground from "../../Assets/headerBackground.png";
const useStyles = makeStyles((theme) => ({
header: {
backgroundImage: `url(${headerBackground})`,
},
}));
export default function Header(props) {
const classes = useStyles();
return (
<AppBar className={classes.header}>
<Toolbar>
<Typography variant="h6">Scroll to Hide App Bar</Typography>
</Toolbar>
</AppBar>
);
}
Material-UI has some components in which there are properties that can be assigned to the image. For example CardMedia - the properties of image. But you can also use the standard tag to insert the image.
<AppBar position="static" color="default" elevation={0} className={classes.appBar}>
<Toolbar className={classes.toolbar}>
<img src="/assets/logo.svg" />
<nav>
<Link variant="button" color="textPrimary" href="#" className={classes.link}>
About
</Link>
</nav>
</Toolbar>
</AppBar>
It works for me.

Resources