I am new to React and I am learning about the props.
My prop doesn't display color on Events.js
I got "I am a car" and red didn't display.
This is my component Welcome.js :
import React from 'react'
import ReactDOM from "react-dom";
function Welcome(props) {
return <h2>I am a {props.color} Car!</h2>;
}
ReactDOM.render(<Welcome color="red"/>, document.getElementById('root'));
export default Welcome;
my page Events.js:
import React, { useState } from "react";
import Calendar from "react-calendar";
import { render } from "react-dom";
import Form from "./Form";
import Welcome from "./Welcome"
function Events() {
const [date, setDate] = useState(new Date());
return (
<div className='app'>
<Form/>
<Welcome/>
</div>
);
}
export default Events;
You are not setting the prop in Events.js. This means the value of props.color is undefined when the render function is called. undefined within curly braces will be ignored by React.
You can add a guard to ensure that you see an error if the prop is not defined:
function Welcome(props) {
if (props.color == null) {
throw 'color should be defined';
}
return <h2>I am a {props.color} Car!</h2>;
}
Related
I have to implement hooks in my Component, but as far as I know it is not possible using the hooks in a REACT.Component.. I am new at REACT and I donĀ“t really have an Idea how I can convert my Component to a function correctly. Can someone show me how to convert the content from my Component to this function?
My Component:
import React from "react";
import { sessionId } from "../common/urlHandler";
import { Settings } from "../settings";
import { Constants } from "../common/constants.js";
import OrderHistoryService from "../services/orderHistory/orderHistoryService";
import OrderHistoryTable from "../orderHistory/orderHistoryTable";
import OrderHistoryPagination from "../orderHistory/orderHistoryPagination";
import OrderHistorySearchField from "../orderHistory/orderHistorySearchField";
export default class OrderHistoryPage extends React.Component {
constructor(props) {
super(props);
const orderHistoryService = new OrderHistoryService(
Settings.baseUrl,
this.props.lang
);
this.state = {
orderHistoryService: orderHistoryService,
sessionId: sessionId(),
orderHistoryData: Constants.DummyOrderHistory,
};
}
componentDidMount() {
//fixMe: fetch-Data and set orderHistoryData
}
render() {
if (this.state.orderHistoryData !== null) {
return (
<section className="section">
<div><OrderHistorySearchField /></div>
<div><OrderHistoryPagination /></div>
<div><OrderHistoryTable orderHistoryData={this.state.orderHistoryData} /></div>
</section>
);
}
}
}
The function into I want to convert my Component:
export default function OrderHistoryPage () {
//fill with data from my Component
}
It should be like this basically you should use useState for states and useEffect for componentDidMount. Also you should remove things that does not exist in functional components like render and this.
import React, {useState, useEffect} from "react";
import { sessionId } from "../common/urlHandler";
import { Settings } from "../settings";
import { Constants } from "../common/constants.js";
import OrderHistoryService from "../services/orderHistory/orderHistoryService";
import OrderHistoryTable from "../orderHistory/orderHistoryTable";
import OrderHistoryPagination from "../orderHistory/orderHistoryPagination";
import OrderHistorySearchField from "../orderHistory/orderHistorySearchField";
export default function OrderHistoryPage (props) {
const orderHistoryService = new OrderHistoryService(
Settings.baseUrl,
props.lang
);
const [orderHistoryService, setorderHistoryService] = useState(orderHistoryService);
const [sessionId, setSessionId] = useState(sessionId());
const [orderHistoryData, setOrderHistoryData] = useState(Constants.DummyOrderHistory);
useEffect(()=> {
//fixMe: fetch-Data and set orderHistoryData
}, []);
return (
{ (orderHistoryData !== null) &&
(<section className="section">
<div><OrderHistorySearchField /></div>
<div><OrderHistoryPagination /></div>
<div><OrderHistoryTable orderHistoryData={this.state.orderHistoryData} /></div>
</section>) }
);
}
import './App.css';
import ComponentC from './components/ComponentC';
export const UserContext = React.createContext()
function App() {
return (
<div className="App">
<UserContext.Provider value={"deneme"}>
<ComponentC />
</UserContext.Provider>
</div>
);
}
export default App;
import React from 'react'
import ComponentE from './ComponentE'
function ComponentC() {
return (
<div>
<ComponentE />
</div>
)
}
export default ComponentC
import React from 'react'
import ComponentF from './ComponentF'
function ComponentE() {
return (
<div>
<ComponentF />
</div>
)
}
export default ComponentE
import React from 'react'
import { UserContext } from "../App"
function ComponentF() {
return (
<div>
<UserContext.Consumer>
{
user => {
return <div>User Context value {user}</div>
}
}
</UserContext.Consumer>
</div>
)
}
export default ComponentF
I have error ReferenceError: React is not defined, I don't understand why I am so new in react.js
so i need some help.
Thanks.
You need to actually pull in the React library somehow, with script tags in your HTML page, such as
<script src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
I'd suggest reviewing the doc's here: https://reactjs.org/docs/getting-started.html#try-react, for suggestions getting started & getting going.
Please import React element from react like
import './App.css';
import React from 'react'; // add line here
export const UserContext = React.createContext();
function App() {
return (
.....
);
}
export default App;
You forgot to add import React from 'react'; at the top thus the error.
I've just started to learn react, I am trying to build a react app with the pokemon api and got the following error: TypeError: pokemon.map is not a function, I am not sure why the .map is not a function in js, does it have something to do with my extensions or the code below? Please help, thank you in advance!
App.js
import React, { useState } from 'react';
import PokemonList from './PokemonList'
function App() {
// eslint-disable-next-line
const [pokemon, setPokemon] = useState("pokemon-1", "pokemon-2")
return (
<PokemonList pokemon={pokemon}/>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
PokemonList.js
import React from 'react';
export default function PokemonList ({pokemon}) {
return (
<div>
{pokemon.map(p =>(
<div key={p}>{p}</div>
))}
</div>
);
}
Pagination.js
import React from 'react';
export default function Pagination() {
return (
<>
</>
);
}
You probably meant to make the default value of the pokemon be an array
const [pokemon, setPokemon] = useState(["pokemon-1", "pokemon-2"])
Notice the square brackets around the two string values ["pokemon-1", "pokemon-2"]
i am trying to include my common component in my main.js
this one I did it it successfully.
but in my common component, I am trying to print my redux data values.
so I created a method called handleClickForRedux to print the values.
I have included mapStateToProps and mapDispatchToProps
but still value is not printing at this line. console.log("event reddux props--->", props);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/react-redux-example-265sd
scroll.js
import React, { useEffect, useState, Fragment } from "react";
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/core/styles";
import Card from "#material-ui/core/Card";
//import CardActions from "#material-ui/core/CardActions";
import CardContent from "#material-ui/core/CardContent";
import Typography from "#material-ui/core/Typography";
import Drawer from "#material-ui/core/Drawer";
import { bindActionCreators } from "redux";
import * as actionCreators from "../actions/actionCreators";
import { connect } from "react-redux";
import { compose } from "redux";
function SportsMouse(classes, props) {
// const [canEdit, setCanEdit] = useState(false);
function handleClickForRedux(event) {
console.log("event--->", event);
console.log("event reddux props--->", props);
}
return (
<Card>
<div onClick={handleClickForRedux}>I am here </div>
</Card>
);
}
SportsMouse.propTypes = {
classes: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
posts: state.posts,
comments: state.comments
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
)
)(SportsMouse);
main.js
import React from "react";
import { Link } from "react-router-dom";
import Scroll from "../commonComponents/scroll";
const Main = props => {
const { children, match, ...rest } = props;
return (
<div>
<h1>
<Scroll />
<Link to="/">Reduxstagram</Link>
</h1>
{React.Children.map(children, child => React.cloneElement(child, rest))}
</div>
);
};
export default Main;
Even when using material-ui, components only accept one argument. classes exists inside props. If you console.log(classes) you'll see that it contains all of your props, including material-ui's styles. It should be this:
function SportsMouse(props) {
I need to test a react components with props mounts ok and renders its content such as paras and divs correctly. My code can be found below or in this sandbox
I tried testing it with a default prop but that didn't work.
import React from 'react';
import test from 'tape';
import {mount} from 'enzyme';
test('testing', t => {
t.doesNotThrow(() => {
wrapper = mount(<App2 txt={ok}/>);
}, 'Should mount');
t.end();
});
And this is my component with props.
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App from './index'
export default class App2 extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
const {txt}=this.props
return (
<div>
<p>hi {txt}</p>
</div>
);
}
}
And the outer component supplying the prop.
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App2 from './app2'
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
<App2 txt={this.state.name}/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
So you would do something like providing the properties yourself and ensuring that it renders with them:
test('test your component', () => {
const wrapper = mount(<App2 txt={'michaelangelo'} />);
expect(wrapper.find('p').text()).toEqual('hi michaelangelo');
});
You shouldn't worry about testing the and html elements like that, but rather the props that you pass and that they render in the right place i.e., in the p tag