i have a random list of 10 dogs and fetching it from api https://dog.ceo/api/breeds/image/random/10 and with every refresh i get another 10 dogs list so my question is how do i make favorite list out of it and show it on another page. I dont want to use Localstorage or redux or context api.
DogHome.js
import "bootstrap/dist/css/bootstrap.min.css";
import "../../Pages/Pages.css";
import DogList from "../Dog/DogList";
import React, { Component } from "react";
class DogHome extends Component {
constructor(props) {
super(props);
this.state = {
dogs: [],
};
}
async componentDidMount() {
try {
const url = "https://dog.ceo/api/breeds/image/random/10";
const response = await fetch(url);
const data = await response.json();
this.setState({ dogs: data.message });
} catch (e) {
console.error(e);
}
}
render() {
return (
<div className="home">
<DogList dogs={this.state.dogs} />
</div>
);
}
}
export default DogHome;
DogList.js
import React from "react";
import Dog from "./Dog";
import "../../Pages/Pages.css";
const DogList = (props) => {
const dogsArray = props.dogs.map((dogURL, index) => {
return <Dog key={index} url={dogURL} />;
});
return (
<>
<div className="doglist">{dogsArray}</div>
</>
);
};
export default DogList;
and lastly here i have a favorite button in every dog image which i want to make favorite on click.
Dog.js
import React from "react";
import { Button } from "react-bootstrap";
import "../../Pages/Pages.css";
const Dog = (props) => {
return (
<div id="child">
<img
style={{ width: 300, height: 300 }}
src={props.url}
alt="ten dogs list"
/>
<Button >Favorite</Button>
</div>
);
};
export default Dog;
You say don't want to use those APIs but you need a method to store favorites. How are you going to decide which are the favorites? How else are you planning to store the values of favorite dogs? You can use a database or a flat file. But you might as well take advantage of some of the React state management if that's your goal.
Could you pleases helping me fix in this problem.
TypeError: Cannot destructure property 'id' of 'this.props.Name' as it is undefined.
src/component/Detail.js file
import React, { Component } from 'react';
import { Character } from './Data_Character/Character';
import Total from './Total';
export default class Detail extends Component {
constructor(props) {
super(props);
this.state = {
names: Character
}
}
render() {
const { names } = this.state;
return(
<div>
{names.map(name => (
<Total key={name.id} Name={name} />
))};
</div>
)
}
}
src/component/Total.js file
import React, { Component } from 'react';
export default class Total extends Component {
render() {
const { id} = this.props.Name;
return(
<div>
{id}
</div>
)
}
}
src/App.js file
import React from 'react';
import './App.css';
import Footer from './component/Footer';
import Detail from './component/Page_ความเป็นมา/Detail';
function App() {
return (
<div className="App">
{/* <Navbar /> */}
{/* <Body /> */}
<Detail />
{/* <Detail_Home /> */}
<Footer />
</div>
);
}
export default App;
Provide a default value, or object, to destructure from const { id } = this.props.Name || {};.
This is even simpler if you convert your Total component to a functional component.
const Total = ({ Name: { id } = {} }) => <div>{id}</div>;
Most likely its because Character doesn't have an id field.
You are passing the contents of Character all the way through (via Name props), but the contents of Character must be omitting id.
You are iterating through the data received from 'Character' object. To do what you do, check if your 'Character' object is in the below format
Character = [{id: 'id1', name: 'Mark'}, {id: 'id2', name: 'John'}]
Character that you are importing in Detail.js must not having id as its property. Check that part or post Character's structure.
I'm pretty sure I'm just 100% missing the point on this as I'm new to React and Javascript but.
When I call another component in my main what is exactly happening with props in these two pieces of code? What is table={table} shouldn't we be calling it props? and then when I pass props to my other component why is it being stored as a const with the point of it being props doesn't it already have those values?
import RecordsGetter from './RecordsGetter'
function MainController() {
const base = useBase();
console.log("The name of the base is: ", base);
const tables = base.tables;
console.log("The name of the tables are: ", tables);
return (
<div>
{tables.map((table) => {
return (
<div>
<br />
<div>{table.name}</div>
<div>{table.id}</div>
<div>{table.description}</div>
<RecordsGetter table={table}/>
</div>
);
})}
</div>
);
}
export default MainController;
import React from 'react';
import {useBase} from '#airtable/blocks/ui'
export default function RecordsGetter (props) {
const {
table
} = props;
const records = useRecords(table);
console.log('records', records);
return (<div></div>)
}
props enable you to pass variables from one to another component down the component tree.
<RecordsGetter table={table}/>
ur passing the recrodsgetter data to another component which then can be read by another component. props can be anything from integers over objects to arrays. Props are read-only. In a functional stateless component, the props are received in the function signature as arguments:
for example:
import React, { Component } from 'react';
class App extends Component {
render() {
const greeting = 'Welcome to React';
return (
<div>
<Greeting greeting={greeting} />
</div>
);
}
}
const Greeting = props => <h1>{props.greeting}</h1>;
export default App;
this is the same thing as
import React, { Component } from 'react';
class App extends Component {
render() {
const greeting = 'Welcome to React';
return (
<div>
<Greeting greeting={greeting} />
</div>
);
}
}
class Greeting extends Component {
render() {
return <h1>{this.props.greeting}</h1>;
}
}
export default App;
the result output would be the same in both cases. we are passing down the parameters of greeting to another component. Which in your case you are passing the table params
New to React - I am trying to use multiple contexts within my App component, I tried following the official guide on multiple contexts.
Here is my current code:
App.js
import React from "react";
import { render } from "react-dom";
import Login from "./Login";
import AuthContext from "./AuthContext";
import LayoutContext from "./LayoutContext";
import LoadingScreen from "./LoadingScreen";
class App extends React.Component {
render() {
const { auth, layout } = this.props;
return (
<LayoutContext.Provider value={layout}>
<LoadingScreen />
<AuthContext.Provider value={auth}>
<AuthContext.Consumer>
{auth => (auth.logged_in ? console.log("logged in") : <Login />)}
</AuthContext.Consumer>
</AuthContext.Provider>
</LayoutContext.Provider>
);
}
}
render(<App />, document.getElementById("root"));
Login.js
import React from "react";
class Login extends React.Component {
render() {
return (
<div></div>
);
}
}
export default Login;
AuthContext.js
import React from "react";
const AuthContext = React.createContext({
logged_in: false
});
export default AuthContext;
LayoutContext.js
import React from "react";
const LayoutContext = React.createContext({
show_loading: false
});
export default LayoutContext;
LoadingScreen.js
import React from "react";
import LayoutContext from "./LayoutContext";
class LoadingScreen extends React.Component {
render() {
return (
<LayoutContext.Consumer>
{layout =>
layout.show_loading ? (
<div id="loading">
<div id="loading-center">
<div className="sk-chasing-dots">
<div className="sk-child sk-dot1"></div>
<div className="sk-child sk-dot2"></div>
</div>
</div>
</div>
) : null
}
</LayoutContext.Consumer>
);
}
}
export default LoadingScreen;
Following the example, I never really understood how this.props (in App.js) could hold my different contexts.
Both auth and layout show up as undefined, this.props is empty, which will in turn cause my app to throw errors such as Cannot read property 'show_loading' of undefined
I immediately liked the example provided in the React documentation, but I can't get this to work.
I've made a small snippet to show you how you could structure your context providers and consumers.
My App component in this case is the root of the app. It has all the providers, along with the value for each one of them. I am not changing this value, but I could if I wanted to.
This then has a single child component, MyOutsideComponent, containing all the chained consumers. There are better ways to do this, I just wanted to show you, one by one, how chaining consumers work. In practice you can neatly reduce this using a few techniques.
This MyOutsideComponent has the actual component, MyComponent, which takes all the context elements and just puts their value on the page. Nothing fancy, the point was to show how the values get passed.
let FirstContext = React.createContext('first');
let SecondContext = React.createContext('second');
let ThirdContext = React.createContext('third');
let FourthContext = React.createContext('fourth');
let MyComponent = (props) => {
return (<span >{Object.values(props).join(" ")}</span>);
};
let App = (props) => {
return (
<FirstContext.Provider value="this is">
<SecondContext.Provider value="how you">
<ThirdContext.Provider value="pass context">
<FourthContext.Provider value="around">
<MyOutsideComponent />
</FourthContext.Provider>
</ThirdContext.Provider>
</SecondContext.Provider>
</FirstContext.Provider>
);
};
let MyOutsideComponent = () => {
return ( < FirstContext.Consumer >
{first =>
(< SecondContext.Consumer >
{second =>
(< ThirdContext.Consumer >
{third =>
(<FourthContext.Consumer >
{fourth =>
(<MyComponent first={first} second={second} third={third} fourth={fourth} />)
}
</FourthContext.Consumer>)
}
</ThirdContext.Consumer>)
}
</SecondContext.Consumer>)
}
</FirstContext.Consumer>);
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Now, for the actual explanation. createContext gives you two actual components: a Provider and Consumer. This Provider, as you found out, has the value. The Consumer takes as child a single function taking one argument, which is your context's value.
This is where the docs are a bit unclear, and a bit which I hope I can help a bit. This does not get passed automatically in props unless the Provider is the direct parent of the component. You have to do it yourself. So, in the example above, I chained four consumers and then lined them all up in the props of my component.
You've asked about class-based components, this is how it ends up looking like:
let FirstContext = React.createContext('first');
let SecondContext = React.createContext('second');
let ThirdContext = React.createContext('third');
let FourthContext = React.createContext('fourth');
class MyComponent extends React.Component {
render() {
return ( < span > {Object.values(this.props).join(" ")} < /span>);
}
}
class App extends React.Component {
render() {
return (
<FirstContext.Provider value = "this is" >
<SecondContext.Provider value = "how you" >
<ThirdContext.Provider value = "pass context" >
<FourthContext.Provider value = "around" >
<MyOutsideComponent / >
</FourthContext.Provider>
</ThirdContext.Provider >
</SecondContext.Provider>
</FirstContext.Provider >
);
}
}
class MyOutsideComponent extends React.Component {
render() {
return (
<FirstContext.Consumer >
{ first =>
(< SecondContext.Consumer >
{ second =>
( < ThirdContext.Consumer >
{ third =>
( < FourthContext.Consumer >
{ fourth =>
( < MyComponent first = {first} second={second} third={third} fourth={fourth} />)
}
</FourthContext.Consumer>)
}
</ThirdContext.Consumer>)
}
</SecondContext.Consumer>)
}
</FirstContext.Consumer>
);
}
}
ReactDOM.render( < App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.
For React 16.8+ you can use the Effect Hook in function components:
import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
document.title = 'My Page Title';
}, []);
}
To manage all valid head tags, including <title>, in declarative way, you can use React Helmet component:
import React from 'react';
import { Helmet } from 'react-helmet';
const TITLE = 'My Page Title';
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.
As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
See: Adding Custom Environment Variables
Since React 16.8. you can build a custom hook to do so (similar to the solution of #Shortchange):
export function useTitle(title) {
useEffect(() => {
const prevTitle = document.title
document.title = title
return () => {
document.title = prevTitle
}
})
}
this can be used in any react component, e.g.:
const MyComponent = () => {
useTitle("New Title")
return (
<div>
...
</div>
)
}
It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.
import React from 'react';
function useTitle(title: string): void => {
React.useEffect(() => {
const prevTitle = document.title;
document.title = title;
return () => {
document.title = prevTitle;
};
}, []);
}
function MyComponent(): JSX.Element => {
useTitle('Title while MyComponent is mounted');
return <div>My Component</div>;
}
This is a pretty straight forward solution, useTitle sets the document title and when the component unmounts it's reset to whatever it was previously.
If you are wondering, you can set it directly inside the render function:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
document.title = 'wow'
return <p>Hello</p>
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
For function component:
function App() {
document.title = 'wow'
return <p>Hello</p>
}
But, this is a bad practice because it will block the rendering (React prioritize the rendering first).
The good practice:
Class component:
class App extends React.Component {
// you can also use componentDidUpdate() if the title is not static
componentDidMount(){
document.title = "good"
}
render() {
return <p>Hello</p>
}
}
Function component:
function App() {
// for static title, pass an empty array as the second argument
// for dynamic title, put the dynamic values inside the array
// see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
useEffect(() => {
document.title = 'good'
}, []);
return <p>Hello</p>
}
React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
you should set document title in the life cycle of 'componentWillMount':
componentWillMount() {
document.title = 'your title name'
},
update for hooks:
useEffect(() => {
document.title = 'current Page Title';
}, []);
Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use:
(modern way React solution - using Hooks)
Create change page title component
import React, { useEffect } from "react";
const ChangePageTitle = ({ pageTitle }) => {
useEffect(() => {
const prevTitle = document.title;
document.title = pageTitle;
return () => {
document.title = prevTitle;
};
});
return <></>;
};
export default ChangePageTitle;
Use the component
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";
...
return (
<>
<ChangePageTitle pageTitle="theTitleYouWant" />
...
</>
);
...
You have multiple options for this problem I would highly recommend to either use React Helmet or create a hook using useEffect. Instead of writing your own hook, you could also use the one from react-use:
React Helmet
import React from 'react';
import { Helmet } from 'react-helmet';
const MyComponent => () => (
<Helmet>
<title>My Title</title>
</Helmet>
)
react-use
import React from 'react';
import { useTitle } from 'react-use';
const MyComponent = () => {
useTitle('My Title');
return null;
}
For React v18+, custom hooks will be the simplest approach.
Step 1: Create a hook. (hooks/useDocumentTitle.js)
import { useEffect } from "react";
export const useDocumentTitle = (title) => {
useEffect(() => {
document.title = `${title} - WebsiteName`;
}, [title]);
return null;
}
Step 2: Call the hook on every page with a custom title according to that page. (pages/HomePage.js)
import { useDocumentTitle } from "../hooks/useDocumentTitle";
const HomePage = () => {
useDocumentTitle("Website Title For Home Page");
return (
<>
<main>
<section>Example Text</section>
</main>
</>
);
}
export { HomePage };
Works well for dynamic pages as well, just pass the product title or whatever content you want to display.
Simply you can create a function in a js file and export it for usages in components
like below:
export default function setTitle(title) {
if (typeof title !== "string") {
throw new Error("Title should be an string");
}
document.title = title;
}
and use it in any component like this:
import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end
class App extends Component {
componentDidMount() {
setTitle("i am a new title");
}
render() {
return (
<div>
see the title
</div>
);
}
}
export default App
You can use the following below with document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'
class App extends Component{
componentDidMount(){
document.title = "Home Page"
}
render(){
return(
<p> Title is now equal to Home Page </p>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
or You can use this npm package npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';
class App extends Component{
render(){
return(
<DocumentTitle title='Home'>
<h1>Home, sweet home.</h1>
</DocumentTitle>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy Coding!!!
I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.
interface Props {
children: string|number|Array<string|number>,
}
export default class DocumentTitle extends React.Component<Props> {
private oldTitle: string = document.title;
componentWillUnmount(): void {
document.title = this.oldTitle;
}
render() {
document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
return null;
}
}
Usage:
export default class App extends React.Component<Props, State> {
render() {
return <>
<DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
<Container>
Lorem ipsum
</Container>
</>
}
}
Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.
By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.
You can use ReactDOM and altering <title> tag
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);
the easiest way is to use react-document-configuration
npm install react-document-configuration --save
Example:
import React from "react";
import Head from "react-document-configuration";
export default function Application() {
return (
<div>
<Head title="HOME" icon="link_of_icon" />
<div>
<h4>Hello Developers!</h4>
</div>
</div>
);
};```
you can create TabTittleHelper.js and
export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};
later you writed all screens
TabTittle('tittleName');
I am not sure if it is a good practice or not, but In index.js headers I put:
document.title="Page Title";
const [name, setName] = useState("Jan");
useEffect(() =>
{document.title = "Celebrate " + {name}.name ;}
);
I wanted to use page title to my FAQ page. So I used react-helmet for this.
First i installed react-helmet using npm i react-helmet
Then i added tag inside my return like this:
import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE }
This is my faq page
)
}
}
If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.