I want to show the Logout button on the same row of the title but only when the user has made it to Home component.
In other words, I don't want to show the logout button at all times, especially when the user's at the login screen. I want it to show on the same row of the title only when they've logged in successfully and they're in Home
How would I achieve this? My head hurts from trying to make this work :(
Below's what I've tried so far, among other things.
import React, {Component} from 'react';
import classes from './Title.css';
import LogoutButton from '../../containers/LogoutButton/LogoutButton';
import Home from '../../components/Home/Home';
class Title extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
showLogoutButton: true
};
}
showButton() {
this.setState({show: true});
if(this.state.show) {
return <LogoutButton/>;
} else {
return null;
}
}
render() {
return(
<div>
{ this.state.showLogoutButton ? this.showButton : null }
<h1 className={classes.Title}>Pick Ups</h1>
</div>
);
}
}
export default Title;
You can try something like below. You don't need to deal with function and modifying states.
You can simply do like below
import classes from './Title.css';
import LogoutButton from '../../containers/LogoutButton/LogoutButton';
import Home from '../../components/Home/Home';
class Title extends Component {
constructor(props) {
super(props);
this.state = {
showLogoutButton: this.props.authenticated
};
}
render() {
const { showLogoutButton } = this.state;
return(
<div className="row" style={{"display" :"flex"}}>
{ showLogoutButton && <LogoutButton/>}
<h1 className={classes.Title}>Pick Ups</h1>
</div>
);
}
}
export default Title;
Note: When you modify state using setState the state value will be updated only after render so you can't directly check immediately modifying the value.
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.
I am trying to write a thing that lets the user move through posts. So you look at a particular post, and then you can go to the previous or next post. I am trying to do this with react router. So say the user looks at posts/3, then by clicking NEXT he or she will be redirected to posts/4 and then see post no. 4.
However, it does not work yet. Clicking the buttons works fine, and it also does change the URL in the browser. However, I do not know how I can then fetch a new post (and populate my currentPost reducer anew), whenever the route changes.
What I have so far is this:
import React from 'react'
import {connect} from 'react-redux'
import {fetchPost} from '../actions/currentPost.js'
class PostView extends React.Component {
constructor(props) {
super(props);
this.setNextPost = this.setNextPost.bind(this);
this.setPreviousPost = this.setPreviousPost.bind(this);
}
componentDidMount() {
const {id} = this.props.match.params;
this.props.fetchPost(id);
console.log("HELLO");
}
setPreviousPost() {
var {id} = this.props.match.params;
id--;
this.props.history.push('/Posts/1');
}
setNextPost() {
var {id} = this.props.match.params;
id++;
this.props.history.push('/Posts/'+id);
}
render() {
return (
<div>
<h1>Here is a Post</h1>
<button onClick={this.setPreviousPost}>Previous</button>
<button onClick={this.setNextPost}>Next</button>
</div>
);
}
}
function mapStateToProps (state) {
return {
currentPost: state.currentPost
};
}
export default connect(mapStateToProps, {fetchPost})(PostView);
The lifecycle method you're looking for is componentWillReceiveProps
Here's more or less what it would look like:
class Component extends React.Component {
componentWillReceiveProps(nextProps) {
const currentId = this.props.id
const nextId = nextProps.id
if (currentId !== nextId) {
this.props.fetchPost(nextId)
}
}
}
from there, I think Redux/React will handle the rest for you.
I have a landing page that contains a logo. I'm trying to get this logo to trigger a change of of state value. The purpose of this is to change from the landing page to the home page on click. I have set it up so that the landing page clear in an determined time, but I want to do this on click. This is my splash.js file that contains the on click function as well as the logo and landing page:
import React, { Component } from 'react';
import Woods from './woods.jpeg';
import Logo1 from './whitestar.png';
export default class Splash extends Component {
constructor() {
super();
this.toggleShowHome = this.toggleShowHome.bind(this);
}
toggleShowHome(property){
this.setState((prevState)=>({[property]:!prevState[property]}))
}
render() {
return(
<div id='Splashwrapper'>
<img src={Woods}></img>
<img id='logoc' src={Logo1} onClick={()=>this.toggleShowHome('showSquareOne')}></img>
</div>
);
}
}
I want the on click function to change the value of splash to false in my App.js file:
import React, { Component } from 'react';
import Splash from './splash';
import Menu from 'components/Global/Menu';
export default class About extends Component {
constructor(){
super();
this.state = {
splash: true
}
}
componentDidMount() {
setTimeout (() => {
this.setState({splash: false});
}, 10000);
}
render() {
if (this.state.splash) {
return <Splash />
}
const { children } = this.props; // eslint-disable-line
return (
<div className='About'>
<Menu />
{ children }
</div>
);
}
}
How can I link the on click function to the App.js file and change the value of splash?
You should define your function toggleShowHome in app.is and pass it as a prop to your splash component. Then you could change your local state in app.js
To make sure I'm understanding, you're looking for the image on the Splash component to trigger a change in the About component?
You can pass a method to your Splash component (from About) that it can call when the image is pressed. So something like this:
render() {
if(this.state.splash) {
return <Splash onLogoClicked={this.logoClicked.bind(this)} />
}
(.......)
}
logoClicked(foo) {
< change state here >
}
And then in your Splash component:
<img id='logoc' src={Logo1} onClick={this.props.onLogoClicked}></img>
Not sure if I understood you well, but you can try this: to pass the on click function from parent (About) to child (Splash), something like this:
YOUR MAIN APP:
export default class About extends Component {
constructor(){
super();
this.state = {
splash: true
}
this.changeSplashState = this.changeSplashState.bind(this);
}
//componentDidMount() {
//setTimeout (() => {
//this.setState({splash: false});
//}, 10000);
//}
changeSplashState() {
this.setState({splash: false});
}
render() {
if (this.state.splash) {
return <Splash triggerClickOnParent={this.changeSplashState} />
}
const { children } = this.props; // eslint-disable-line
return (
<div className='About'>
<Menu />
{ children }
</div>
);
}
}
YOUR SPLASH COMPONENT:
export default class Splash extends Component {
constructor() {
super();
//this.toggleShowHome = this.toggleShowHome.bind(this);
}
toggleShowHome(property){
this.setState((prevState)=>({[property]:!prevState[property]}));
//IT'S UP TO YOU TO DECIDE SETTING TIMOUT OR NOT HERE
//setTimeout (() => {
this.props.triggerClickOnParent();
//}, 10000);
}
render() {
return(
<div id='Splashwrapper'>
<img src={Woods}></img>
<img id='logoc' src={Logo1} onClick={this.toggleShowHome.bind(this,'showSquareOne')}></img>
</div>
);
}
}
Feel free to post here some errors or explain to me more about what you need, but that is the way it should look like, a standard way to pass function as props from parent to child.
You can also read more about how to pass props from parent to child/grandchild/many-deeper-level-child (of course in react's way):
Force React container to refresh data
Re-initializing class on redirect
I've gone through many of the Redux and ReactJS tuts. I understand setting actions => action creators => dispatch => store => render view (uni-directional flow) with more data substantial events. My problem is dealing with very simple events that change state. I know not all state always needs to be handled in Redux, and that local state events (set on React components) is an acceptable practice. However, technically Redux can handle all state events and this is what I am trying to do.
Here is the issue. I have a React component that renders a Button. This Button has an onClick event that fires a handleClick function. I set the state of the Button via the constructor method to isActive: false. When handleClick fires, setState sets isActive: true. The handleClick method also runs two if statements that, when either evaluate to true, run a function that either changes the background color of the body or the color of paragraph text. Clicking the same button again sets state back to false and will change back the body color or text color to the original value. This Button component is created twice within a separate component, Header. So long story short, I've got two buttons. One changes body color, the other changes p tag color after a click event.
Here's the code for the Button component:
import React, {Component} from 'react';
import {dimLights, invertColor} from '../../../actions/headerButtons';
import { connect } from 'react-redux';
import { Actions } from '../../../reducers/reducer';
const headerButtonWrapper = 'headerButton';
const headerButtonContext = 'hb--ctrls ';
const dimmedLight = '#333333';
const invertedTextColor = '#FFFFFF';
export default class Button extends Component {
constructor (props) {
super(props)
this.state = {
isActive: false
};
}
handleClick (e) {
e.preventDefault();
let active = !this.state.isActive;
this.setState({ isActive: active });
if(this.props.label === "Dim The Lights"){
dimLights('body', dimmedLight);
}
if(this.props.label === "Invert Text Color"){
invertColor('p', invertedTextColor)
}
}
render() {
let hbClasses = headerButtonContext + this.state.isActive;
return (
<div className={headerButtonWrapper}>
<button className={hbClasses} onClick={this.handleClick.bind(this)}>{this.props.label}</button>
</div>
);
}
}
Here's the code for the imported functions that handle changing the colors:
export function dimLights(elem, color) {
let property = document.querySelector(elem);
if (property.className !== 'lightsOn') {
property.style.backgroundColor = color;
property.className = 'lightsOn'
}
else {
property.style.backgroundColor = '#FFFFFF';
property.className = 'lightsOff';
}
}
export function invertColor(elem, textColor) {
let property = document.querySelectorAll(elem), i;
for (i = 0; i < property.length; ++i) {
if (property[i].className !== 'inverted') {
property[i].style.color = textColor;
property[i].className = 'inverted'
} else {
property[i].style.color = '#3B3B3B';
property[i].className = 'notInverted';
}
}
}
Here's the code for the reducers:
import * as types from '../constants/ActionTypes';
const initialState = {
isActive: false
};
export default function Actions(state = initialState, action) {
switch (action.type) {
case types.TOGGLE_LIGHTS:
return [
...state,
{
isActive: true
}
]
default:
return state
}
}
Here's the code for the actions:
import EasyActions from 'redux-easy-actions';
export default EasyActions({
TOGGLE_LIGHTS(type, isActive){
return {type, isActive}
}
})
If it helps, here's the Header component that renders two Button components:
import React, {Component} from 'react';
import Button from './components/Button';
const dimmer = 'titleBar--button__dimmer';
const invert = 'titleBar--button__invert';
export default class Header extends Component {
render() {
return (
<div id="titleBar">
<div className="titleBar--contents">
<div className="titleBar--title">Organizer</div>
<Button className={dimmer} label="Dim The Lights" />
<Button className={invert} label="Invert Text Color" />
</div>
</div>
);
}
}
Finally, here's the code containing the store and connection to Redux (NOTE: Layout contains three main components Header, Hero, and Info. The Buttons are created only within the Header component)
import React, { Component } from 'react';
import { combineReducers } from 'redux';
import { createStore } from 'redux'
import { Provider } from 'react-redux';
import Layout from '../components/Layout';
import * as reducers from '../reducers/reducer';
const reducer = combineReducers(reducers);
const store = createStore(reducer);
// This is dispatch was just a test to try and figure this problem out
store.dispatch({
type: 'TOGGLE_LIGHTS',
isActive: true
})
console.log(store.getState())
export default class Organizer extends Component {
render() {
return (
<Provider store={store}>
<div>
<Layout />
</div>
</Provider>
);
}
}
What I am looking to do is remove the state logic from the local React component and into Redux. I feel like the functions I have imported need to act as dispatchers. I also feel like I am setting up my initial actions incorrectly. This is such an incredibly simple event that finding an answer anywhere online is difficult. Anyone have any thoughts on what I can do to fix this?
You're almost there. It looks like you've left out the code for Layout component, which I assume is the component that's rendering your Button. The critical piece here is going to be your container, which is the component that's wrapped with Redux's connect to link it to the store. Docs for this. More details here.
What you did:
// components/Button.js - pseudocode
import {dimLights, invertColor} from '../../../actions/headerButtons';
handleClick() {
dimLights();
}
What Redux wants you to do instead:
// containers/App.js - pseudocode
import {dimLights, invertColor} from '../../../actions/headerButtons';
class App extends Component {
render() {
// Pass in your button state from the store, as well as
// your connected/dispatch-ified actions.
return (
<Button
state={this.props.buttonState}
onClick={this.props.buttonState ? dimLights : invertColor}
/>
);
}
}
function mapStateToProps(state, ownProps) {
return {
buttonState: state.buttonState
};
}
export default connect(mapStateToProps, {
// Your action functions passed in here get "dispatch-ified"
// and will dispatch Redux actions instead of returning
// { type, payload }-style objects.
dimLights, invertColor
})(App);
Hope that helps! Redux has a lot of boilerplate for simple stuff like this, however, because most of the pieces can be expressed as pure functions, you gain a lot in unit testing flexibility, and get to use the devtools debugger.