update: i removed this from this.props. but now nothing is showing in the localhost.
i am trying to write a blog page in react. Here is my blog.js:
import React from 'react'
const Blog=props=>{
const {title,author,content}=this.props
return(
<div>
<h2>{title}</h2>
<h5><i>{author}</i></h5>
<br/>
<h3>{content}</h3>
</div>
)
}
export default Blog
and my App.js is below:
import React,{Component} from 'react';
import Blog from './Blog'
class App extends Component {
render(){
const posts=[
{
title:'First',
author:'Anonymous',
content:'first Post',
},
{
title:'Second',
author:'Anonymous',
content:'Second Post',
},
{
title:'third',
author:'Anonymous',
content:'Second Post',
},
]
return (
<div className="container">
<Blog postData={posts}/>
</div>
);
}
}
export default App ;
while i excute npm start there is no error but in the broswer it is saying:
TypeError: Cannot read property 'props' of undefined
Blog
C:/Myfiles/python/Django/djangorest/booklearn/test-cases/src/Blog.js:5
2 |
3 |
4 | const Blog=props=>{
> 5 | const {title,author,content}=this.props
6 | return(
7 |
8 | <div>
i am running out of options. How can i solve this thing?
i have started reactjs very recent. any advice will be much appreciated.
You are using a functional component and passing in props as an argument to your function (props =>). You do not need to use this.props just props will work.
You are passing in an array of posts under the prop name 'postData'. In your blog component you need to:
import React from 'react'
const Blog=props=>{
return props.postData.map((post) => {
const { title, author, content } = post;
return (
<div key={title}>
<h2>{title}</h2>
<h5><i>{author}</i></h5>
<br/>
<h3>{content}</h3>
</div>
);
});
}
export default Blog;
Remove this since its not a class and props are being passed as the first parameter of the function.
import React from 'react'
const Blog = (props) => {
const { title,author,content } = props;
return(
<div>
<h2>{title}</h2>
<h5><i>{author}</i></h5>
<br/>
<h3>{content}</h3>
</div>
)
}
export default Blog
Related
I have a simple react app in which i have to use useContext.
(btw im using vite + react)
here is my code for Context.jsx
import React, {useContext} from 'react';
const emailContext = React.createContext();
export const useEmail = () => useContext(emailContext);
export const emailProvider = ({children}) => {
const currentUser = "None";
const value = {
currentUser
}
return(
<emailContext.Provider value={value}>
{children}
</emailContext.Provider>
)
}
and heres how i am using the context
import "./styles.css";
import { useEmail } from "./Context/Context"
export default function App() {
const {currentUser} = useEmail();
return (
<div className="App">
<h1>Hello CodeSandbox {currentUser}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
I am sure why I am getting error in this code.
some of the errors that I am getting
_useEmail is undefined (latest)
currentUser user is undefined
thing i have tried
Initialized createContext with some initial value (only intial value is visible).
using useContext() directy in the App.js (useContext(emailContext) return undefined)
instead of {children} used <children/>.
used useState instead of const currentUser in emailProvider
I am getting same problem even when I use typescript.
but none of the above helped.
You should wrapping app with <emailProvider></emailProvider> to using data in value={value}. Now it gets undefined from const emailContext = React.createContext();
Below code may help you analyse the flow , also check link for more details https://medium.com/technofunnel/usecontext-in-react-hooks-aa9a60b8a461
use useContext in receiving end
import React, { useState } from "react";
var userDetailContext = React.createContext(null);
export default function UserDetailsComponent() {
var [userDetails] = useState({
name: "Mayank",
age: 30
});
return (
<userDetailContext.Provider value={userDetails}>
<h1>This is the Parent Component</h1>
<hr />
<ChildComponent userDetails={userDetails} />
</userDetailContext.Provider>
);
}
function ChildComponent(props) {
return (
<div>
<h2>This is Child Component</h2>
<hr />
<SubChildComponent />
</div>
);
}
function SubChildComponent(props) {
var contextData = React.useContext(userDetailContext);
return (
<div>
<h3>This is Sub Child Component</h3>
<h4>User Name: {contextData.name}</h4>
<h4>User Age: {contextData.age}</h4>
</div>
);
}
EDIT
Updated and installed the lib with its updated newer package, but now getting the following error,
TypeError: Cannot read property 'default' of undefined
Function.mapStateToProps [as mapToProps]
node_modules/react-redux-loading-bar/build/loading_bar.js:300
297 |
298 | var mapStateToProps = function mapStateToProps(state, ownProps) {
299 | return {
> 300 | loading: state.loadingBar[ownProps.scope || _loading_bar_ducks.DEFAULT_SCOPE]
301 | };
302 | };
303 |
PREVIOUS:
I am using React Redux Loading Bar from TylerMcginnis here. Please note that I am not using loading bar middleware but instead a dispatch. What am I missing or doing wrong?
TypeError: state.loadingBar is undefined
Uncaught TypeError: state.loadingBar is undefined
Redux 7
React 3
ConnectFunction Redux
React 18
js index.js:20
Webpack 7
Here is the code,
import React, { Fragment } from 'react';
import { connect } from 'react-redux';
// import LoadingBar from 'react-redux-loading';
import LoadingBar from 'react-redux-loading-bar';
function Login({ users, userKeys, loading }) {
return (
<Fragment>
<LoadingBar />
<div className='container'>
{loading ? null : (
<div>
<label htmlFor='users'>Please select a User</label>
<br />
<select id='users' name='usersList'>
{userKeys.map(id => (
<option value={id}>{users[id].name}</option>
))}
</select>
</div>
)}
</div>
</Fragment>
);
}
function mapStateToProps({ users }) {
return {
loading: users === null,
users,
userKeys: Object.keys(users)
};
}
export default connect(mapStateToProps)(Login);
Reducers index:
import { combineReducers } from "redux";
import { loadingBarReducer } from 'react-redux-loading-bar';
import questions from './questions';
import users from './users';
export default combineReducers({
loadingBarReducer,
questions,
users
});
action :
export function handleInitialData() {
return dispatch => {
dispatch(showLoading());
return getInitialData().then(({users, questions}) => {
dispatch(receiveQuestions(questions));
dispatch(receiveUsers(users));
dispatch(hideLoading());
});
};
}
Fixed the issue while creating a sandbox example for you all :D...
Main Issue:
reducer should have object/field name as loadingBar for the library to be able to recognize the reducer.
This one little change fixed the issue in reducer,
export default combineReducers({ users, loadingBar: loadingBarReducer });
Here is sandbox link
I am testing out how to use Context in React but for some reason I cant run the app due the typescript error I get!
Code:
import React from 'react';
import './App.css';
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
function Toolbar(props) {
// The Toolbar component must take an extra "theme" prop
// and pass it to the ThemedButton. This can become painful
// if every single button in the app needs to know the theme
// because it would have to be passed through all components.
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
class ThemedButton extends React.Component {
render() {
return <button className={'btn btn-' + this.props.theme}></button>;
}
}
export default App;
Error I get:
C:/Users/as/Desktop/React - Mobx -Hooks/react-hooks-mobx/src/App.tsx
TypeScript error in C:/Users/iluli/Desktop/React - Mobx -Hooks/react-hooks-mobx/src/App.tsx(11,20):
Parameter 'props' implicitly has an 'any' type. TS7006
9 | }
10 |
> 11 | function Toolbar(props) {
Any idea how to fix this and explain the reason why it throws that error?
You just need to provide the Type for it:
import React from "react";
import "./App.css";
interface IToolbarProps {
theme: string;
}
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
// Here in the function
function Toolbar(props: IToolbarProps) {
// The Toolbar component must take an extra "theme" prop
// and pass it to the ThemedButton. This can become painful
// if every single button in the app needs to know the theme
// because it would have to be passed through all components.
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
// HERE as a generic
class ThemedButton extends React.Component<IToolbarProps> {
render() {
return <button className={"btn btn-" + this.props.theme}></button>;
}
}
export default App;
I am trying to understand how Props work in React. The following code is giving an error - Error: Objects are not valid as a React child (found: object with keys {args})
const App = () => {
const course = 'Half Stack application development'
return (
<div>
<Header args={course}/> // Will an object be passed or just the string?
</div>
)
}
const Header = (agrs)=>{
console.log(agrs)
return (
<div>
<h1>{agrs}</h1>
</div>
)
}
When props are being passed, is an Object is passed encapsulating the fields or just the field values are passed?
why does the above code doesn't work?
Thanks
First off, you have a spelling mistake. Replace agrs with args. Secondly, props are passed as an object (dictionary), so you have one of two options:
const Header = (props) =>{
console.log(props.args)
return (
<div>
<h1>{props.args}</h1>
</div>
)
}
or object destructuring:
const Header = ({args}) =>{
console.log(args)
return (
<div>
<h1>{args}</h1>
</div>
)
}
Also, make sure to add props validation (your linter should warn you about this):
import PropTypes from "prop-types";
Header.propTypes = {
args: PropTypes.string.isRequired
};
Answer 1: Value is passed as a key with the same name as field you assigned it to in props object.
Answer 2:
const Header = (props)=>{
console.log(props.agrs)
return (
<div>
<h1>{props.agrs}</h1>
</div>
)
}
The code above will run fine.
Alternative to answer 2:
const Header = ({agrs})=>{
console.log(agrs)
return (
<div>
<h1>{agrs}</h1>
</div>
)
}
This will also run fine.
It uses object destructuring so you don't have to use props.agrs but just args works fine.
const App = () => {
const course = 'Half Stack application development'
return (
<div>
<Header args={course}/> // Will an object be passed or just the string?
</div>
)
}
const Header = ({agrs})=>{
console.log(agrs)
return (
<div>
<h1>{agrs}</h1>
</div>
)
}
Use object Destructuring like above or
const Header = (props)=>{
console.log(props.agrs)
return (
<div>
<h1>{props.agrs}</h1>
</div>
)
}
Find more here Components and Props.
Find more about Destructuring
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('app'));
export default App;
enter image description here
I edited code that was working perfectly fine, until I added new code to make the button clicking work from video to video. I just can't find the error, and the terminal is not picking it up either.
Can someone tell me why the ./video_list_item.js is not being recognized anymore?
Attached is the parent, and 2 child components, though I have 5 total components the error is definitely only in one of the two.
index.js
import React, {Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/searchbar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
const API_KEY = 'AIzaSyAi1CzVpifuFUDVQf3dzrTu3mwJDP2n8r8';
class App extends Component {
constructor(props){
super(props);
//Do i expect this component to play any type of state? aka pass props
this.state= {
videos: [],
selectedVideo:null
};
// ^proper name can be anything
YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
// console.log(data);
this.setState({ videos:videos,
selectedVideo: videos[0]
});
}); // this.setState({videos : vidoos});
}
render (){
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
video_list.js
//video list file. JS.react
import React from 'react';
import VideoListItem from './video_list_item';
const VideoList = (props) => {
// ^props is made args here because videos var is passed
// in index.js into VideoList function(with state).
const videoItems = props.videos.map((video) => {
return (
<VideoListItem
onVideoSelect={props.onVideoSelect}
key={video.etag}
video ={video} />
);
});
return (
<ul className="col-md-4 list-group">
{videoItems}
</ul>
);
};
export default VideoList;
video_list.item.js
//video list item file. JS.react
import React from 'react';
const VideoListItem = ({video, onVideoSelect}) => {
const imageUrl = video.snippet.thumbnails.default.url;
// can see this in console log
return (
<li onClick={() => onVideoSelect{video} }className="list-group-item">
<div className ="video-list media">
<div className ="media-left">
<img className="media-object" src = {imageUrl}/>
</div>
<div className="media-body">
<div className="media-heading"> {video.snippet.title} </div>
</div>
</div>
</li>
);
};
export default VideoListItem;
I can post the error message I get in the dev tools, but it literally just says one thing. This is the error message => Cannot find module "./video_list_item"
Also, no files were moved around at all, the code was edited and that created the error message. Thanks for anyone who sincerely answers this question!
<li onClick={() => onVideoSelect{video} }className="list-group-item">
The error is the {video} should actually be in parenthesis like so (video).
correct code is:
<li onClick={() => onVideoSelect(video) }className="list-group-item">.
Note: The {} makes it so the child component is not recognized by the parent for some strange reason. Thanks to all those who helped in answering!