Problem: when the page first loads up, the PageHeader H1 tag shows a blank value instead of "New Page". Why does this happen and how can I make it show "New Page"?
In Page.js
const [pageTitle, setPageTitle] = useState('New Page');
const pageTitleChangeHandler = (e) => {
setPageTitle(e.target.innerText);
}
return (
<PageHeader title = {pageTitle} onChange = {pageTitleChangeHandler}></PageHeader>
);
In PageHeader.js
return (
<div className = "page-header">
<h1
className = "page-header-text"
contentEditable = "true"
onInput = {props.onChange}
value = {props.title}>
</h1>
</div>
);
CodePudding user response:
I think you should remove value
attribute from h1 tag and set dangerouslySetInnerHTML
instead like
import React from "react";
export default function PageHeader(props) {
return (
<div className="page-header">
<h1
className="page-header-text"
contentEditable="true"
onInput={props.onChange}
dangerouslySetInnerHTML={{ __html: props.title }}
>
</h1>
</div>
);
}
CodePudding user response:
If you want New Page
to show up on page load, you need to change the argument to setPageTitle
from e.target.innerText
to e.target.value
, and add {props.title}
in the h1
tag.
Then you can change onInput
to onKeyDown
.
const [pageTitle, setPageTitle] = useState('New Page');
const pageTitleChangeHandler = (e) => {
// This will set the value prop
setPageTitle(e.target.value);
}
return (
<PageHeader
title={pageTitle}
onChange={pageTitleChangeHandler}
></PageHeader>
);
}
const PageHeader = (props) => {
return (
<div className="page-header">
<h1
className="page-header-text"
contentEditable="true"
onKeyDown={props.onChange}
value={props.title}
>
{props.title}
</h1>
</div>
);
Note that this will delete "New Page" and replace it with the typed text.