React Newbee here
Firstly , I have a component DetailMovieCard.jsx where I am inserting background image in componentDidMount () It works fine but I was wondering is there any other efficient way instead of using
document.body.style.backgroundImage
DetailMovieCard.jsx
import React, { Component } from "react";
import { Row, Col, Glyphicon, Button } from "react-bootstrap";
import styled from "styled-components";
import { URL_IMAGE, URL_BACKGROUND } from "../const";
const Wrapper = styled.div`
max-width: 60%;
overflow: hidden; `;
const Image = styled.img`
float: left;
width: 40%;
`;
class DetailMovieCard extends Component {
componentDidUpdate() {
document.body.style.backgroundImage =
`url(${URL_BACKGROUND}${this.props.movie.backdrop_path})`;}
render() {
const {
poster_path, original_title, backdrop_path, tagline, overview,
} = this.props.movie;
return (
<Wrapper>
<Image alt="" src={`${URL_IMAGE}${poster_path}`} />
<div className="movie-details">
<h3>Title of the movie is {original_title} </h3>
<div>
<div className="movie-tagline"> {tagline} </div>
<div className="movie-overview">{overview} </div>
</div>
</div>
</Wrapper>
);
}
}
export default DetailMovieCard;
Secondly , I have a component called MovieDetails.jsx currently I am giving data fetched by componentDidMount() directly to <DetailMovieCard movie={this.state.movieData} > again it works fine but is there any better way of doing it ?
import React, { Component } from "react";
import axios from "axios";
import { URL_DETAIL, API_KEY } from "../const";
import DetailMovieCard from './DetailMovieCard';
import Header from './Header';
class MovieDetails extends Component {
constructor(props) {
super(props);
this.state = {
movieData: { movies: " " }
};
}
componentDidMount() {
const { id } = this.props.match.params;
axios.get(`${URL_DETAIL}${id}${API_KEY}&language=en-US&page=1`)
.then(response => {
this.setState({ movieData: response.data });
});}
render() {
return (
<div className= "movie-container">
<Header/>
<DetailMovieCard movie={this.state.movieData} />
</div>
);
}
}
export default MovieDetails;
You can always use callbacks:
Set the backgroundImage in your main App component there is no reason to use <body>
Keep the current backgroundImage url in main App component state or in redux store
Then you can set the backgroundImage url using regular javascript callbacks
Related
Component, myImage is never read.
import React from 'react';
import { Box } from "#mui/material";
import { Link } from 'react-router-dom';
import myImage from './Profile/Profile.myImage';
const HomeProfile = () => {
return (
<Box sx={{ border: '1px dashed grey' }}>
<myImage />
<Link to="/app/profile" className="red btn-flat white-text">
Change Profile
</Link>
</Box>
)
}
export default HomeProfile;
This is the file './Profile/Profile.myImage':
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchProfile } from '../../../actions';
import { Image } from 'react-bootstrap';
import axios from 'axios';
class myImage extends Component {
componentDidMount() {
this.props.fetchProfile();
}
async renderMyImage() {
const imageDir = await axios.get('/api/profile');
return (
<div>
<h1>hello</h1>
<Image src={imageDir.profileImg.type} />
</div>
);
}
render() {
return (
<div>
<div>{this.renderMyImage()}</div>
<h1>bye</h1>
</div>
);
}
}
function mapStateToProps({ user }) {
return { user };
}
export default connect(mapStateToProps, {fetchProfile})(myImage);
In the route.js, app.get('/api/profile') is defined like this.
however, nothing appears in the console.
app.get('/api/profile', requireLogin, async(req, res) => {
console.log('test: api/profile');
const profile = await User.find({ _user: req.user.id });
res.send(profile);
})
I thought, something was wrong in the function 'renderMyImage()', so I added "hello" and "bye", but still, nothing is on the view, while other components can be seen on the screen.
axios is async so renderMyImage should be an async function.
Have you tried
async renderMyImage() {
const imageDir = await axios.get('/api/profile');
return (
<div>
<h1>hello</h1>
<Image src={imageDir.profileImg.type} />
</div>
);
}
Hi i am stuck in a problem when Am trying to display movie image in top of the webpage its isn't showing don't know where i am wrong please help
i want to display movie banner top of the webpage
https://ibb.co/QprbB5n
Banner.js
This is my Banner page where i wrote whole logic
import React, { Component } from 'react';
import './Banner.css';
import Request from './Request';
import Axios from 'axios';
class Banner extends React.Component {
constructor(props) {
super(props)
this.state = {
movies: []
}
}
fetchData = async () => {
const movies = await Axios.get(Request.fetchNetflixOriginals)
this.setState({
movies: movies.data.results[
Math.floor(Math.random() * movies.data.results.length - 1)
]
});
console.log(movies);
return movies;
}
componentDidMount() {
this.fetchData();
}
render() {
// const {movies} = this.state
return (
<header className='banner'
style={{
backgroundSize: 'cover',
backgroundImage: `url(
"https://image.tmdb.org/t/p/original/${this.props.movies?.backdrop_path}"
)`,
backgroundPosition: 'center center',
}}
>
<div className='banner-contents'>
<h1>
{this.props.movies?.title || this.props.movies?.name || this.props.movies?.original_name}
</h1>
<div className='banner_button'>
<button className='banner_button'>Add</button>
<button className='banner_button'>Delete</button>
</div>
</div>
</header>
)
}
}
export default Banner;
I am trying to use a component that is already created, but I cant figure out what the problem is:
activetenant
import React, { Component } from 'react';
import authAction from '../../redux/auth/actions';
class ActiveTenant extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div></div>
);
}
}
export default ActiveTenant;
and the component where I am trying to use it
import React, { Component } from "react";
import { connect } from "react-redux";
import { Layout } from "antd";
import appActions from "../../redux/app/actions";
import TopbarUser from "./topbarUser";
import TopbarWrapper from "./topbar.style";
import themes from "../../settings/themes";
import { themeConfig } from "../../settings";
import { ActiveTenant } from "./activetenant";
const { Header } = Layout;
const { toggleCollapsed } = appActions;
const customizedTheme = themes[themeConfig.theme];
class Topbar extends Component {
render() {
const { toggleCollapsed } = this.props;
const collapsed = this.props.collapsed && !this.props.openDrawer;
const styling = {
background: customizedTheme.backgroundColor,
position: "fixed",
width: "100%",
height: 70
};
return (
<TopbarWrapper>
<Header
style={styling}
className={
collapsed ? "isomorphicTopbar collapsed" : "isomorphicTopbar"
}
>
<div className="isoLeft">
<button
className={
collapsed ? "triggerBtn menuCollapsed" : "triggerBtn menuOpen"
}
style={{ color: customizedTheme.textColor }}
onClick={toggleCollapsed}
/>
</div>
<ul className="isoRight">
<li>
<ActiveTenant />
</li>
<li
onClick={() => this.setState({ selectedItem: "user" })}
className="isoUser"
>
<TopbarUser />
</li>
</ul>
</Header>
</TopbarWrapper>
);
}
}
export default connect(
state => ({
...state.App.toJS()
}),
{ toggleCollapsed }
)(Topbar);
And the error
./src/containers/Topbar/Topbar.js 105:34-46 './activetenant' does not
contain an export named 'ActiveTenant'.
You are use export default ActiveTenant In this case code should be like this
import ActiveTenant from "./activetenant";
If you want to export mulitple value then use {} to import
for example
//test.js
var a = "cool";
var b = "dool";
export a;
export b;
import {a,b} from './test.js'
First of all, I want to ask whether is my statement is correct :
"When we are making components, it is better to put it in different files"
Is it correct? since currently I tried so, and it cause problems.
Parents :
import React, { Component } from 'react';
import './App.css';
import {SubmitComponent} from './submitComponent.jsx';
import {topicTable} from './topicTable.jsx';
// import {TopicsContainer} from './TopicsContainer.js'
const dashboardStyle = {
border: '2px solid black',
width: '70%',
height: 'auto',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: '100px',
};
class AppDashBoard extends Component {
constructor(props) {
super(props);
this.state = {
datas: []
}
}
submitTopic = (data) => {
console.log(data);
console.log(this.state.datas);
console.log(this.state.datas.concat([data]));
this.setState({
datas: this.state.datas.concat(data)
});
console.log(this.state.datas);
}
render() {
return (
<div style={dashboardStyle}>
<h1 style={{textAlign:'center'}}>Coding Exercise</h1>
<hr />
<SubmitComponent submitTopic={this.submitTopic} />
<topicTable topics={this.state.datas} />
</div>
);
}
}
export default AppDashBoard
and this is the topicTable component :
import React, {Component} from 'react';
import {oneTopic} from './oneTopic.jsx';
export class topicTable extends Component {
render() {
const topicstable = this.props.topics.map((topic) => (
<oneTopic
title={topic.title}
desc = {topic.desc}
vote = {topic.vote}
/>
));
console.log("HAHAHAHA");
return (
<div id="topics">
{oneTopic}
</div>
);
}
}
and Lastly, my oneTopic component:
import React, {Component} from 'react';
export class oneTopic extends Component {
render() {
return(
<div style={{width:'96%', height:300, backgroundColor :'#AAA'}}>
<h1>HAHAHAHA</h1>
</div>
);
}
}
My problems are :
1) In the topicTable component, the console.log("HAHAHA") is not executed at all, I wonder why ?
2) Also for the oneTopic, the HAHAHA is not showing at all.
Even I already export and import everything
Please help
ReactJS component names must begin with capital letters.
1) rename oneTopic to OneTopic
2) change {oneTopic} to <oneTopic />
im using react with react-redux and react-router. im working on my blog, in which i have a component with shows list of posts. so everything is working fine but when i get post.id in component it gives me undefined. on the other hand posts are passing to component from container.
please look into my code.
//home_container.js
import { connect } from 'react-redux'
import { show } from './actions'
import HomeComponent from './home_component'
const mapStateToProps = (state) => {
return {
posts: state.posts.data
}
}
const mapDispatchToProps = (dispatch) => {
return {
actions:{
showPosts: (page,limit) => {
show(dispatch,page,limit)
}
}
}
}
const HomeContainer = connect(
mapStateToProps,
mapDispatchToProps
)(HomeComponent)
export default HomeContainer
//home_component.js file
import React, {Component} from 'react';
import Paper from 'material-ui/Paper';
import Style from './styles.css'
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router'
require('rc-pagination/assets/index.css');
const Pagination = require('rc-pagination');
const style = {
height: "100%",
margin: 10,
padding: 10,
display: 'inline-block',
};
var Detail = React.createClass({
render: function() {
return (
<div >
<div className="row">
<div >
<p>{this.props.post?this.props.post.body.substr(1,600):''}</p>
{this.props.post?
<span style={{"float":"right"}}>
<Link to={`/posts/${this.props.post.id}`}>
<FlatButton
label="Ready more"
labelPosition="before"
primary={true}
/>
</Link>
</span>
:''}
</div>
</div>
</div>
)
}
});
class Index extends Component {
getChildContext() {
return { muiTheme: getMuiTheme(baseTheme) };
}
componentDidMount(){
this.props.actions.showPosts(1,5)
}
render() {
return (
<div >
{this.props.posts.map((post,i) =>
<div className="row" key={i}>
<Paper
style={style}
zDepth={0}
children={<Detail post={post}/>}
/>
)}
</div>
);
}
}
Index.childContextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
export default Index;
i already check through react-redux inspector. i have posts in posts props of this component, which are sets by container through react redux.
so problem is in the following part of above code.
<Link to={`/posts/${this.props.post.id}`}>
<FlatButton
label="Ready more"
labelPosition="before"
primary={true}
/>
</Link>
Link to tag of react router generate url in this form posts/undefined. because it is considering that post.id is undefined. on the other hand each post have id property and i also checked it through inspection of posts objects.
so problem is in this line this.props.post.id