React JSX - make substring in bold
First, you need to find and extract the appropriate substring (the string you are looking for) if exits in given list and make a custom string by extracting that substring as given below.
//autoValue - value you are looking for
//main - item value
const val =
main.slice(0, main.indexOf(autoValue)) +
"<b>" +
autoValue +
"</b>" +
main.slice(
main.indexOf(autoValue) + autoValue.length,
main.length
);
Now, You have to use dangerouslySetInnerHTML
for a span
or any custom HTML
component you are using for rendering each item in you auto-complete component.
Here is full example.
const items = [
"React",
"Angular",
"Vue",
"Node",
"Express",
"PHP",
"Laravel",
"Material",
"CSS",
"HTML"
];
function ListItem(props) {
if (props.value.indexOf(props.autoValue) > -1 && props.autoValue.length > 0) {
const main = props.value;
const val =
main.slice(0, main.indexOf(props.autoValue)) +
"<b>" +
props.autoValue +
"</b>" +
main.slice(
main.indexOf(props.autoValue) + props.autoValue.length,
main.length
);
return (
<div>
<span dangerouslySetInnerHTML={{ __html: val }} />
<hr />
</div>
);
} else {
return (
<span>
{props.value}
<hr />
</span>
);
}
}
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map(number => (
<ListItem
key={number.toString()}
value={number}
autoValue={props.autoValue}
/>
));
return <div>{listItems}</div>;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ""
};
this.update = this.update.bind(this);
}
update(e) {
e.preventDefault();
this.setState({ inputValue: e.target.value });
}
render() {
return (
<div>
<input
type="text"
onChange={this.update}
name="inputValue"
value={this.state.inputValue}
/>
<NumberList numbers={items} autoValue={this.state.inputValue} />
<span> {this.state.inputValue} </span>
</div>
);
}
}
export default App;
Working Example. https://codesandbox.io/s/n9n65wqj5j
How to bold specific text in a string in a React.js app
You need to dangerouslySetInnerHTML
Sample code below. This is what it does.
- Make all text bold via CSS
- Our keyword is wrapped in a
i
tag. This is rendered with normal font weight via a CSS rule.
Please note that below is a code sample to be used in react context/OP application, this will not work in this site.
const makeBold = (item, keyword) => {
var re = new RegExp(keyword, 'g')
return (
item.replace(re, '<i>'+keyword+ '</i>')
)
}
console.log(makeBold('blue shoes', 'blue'));
.text-bold {
font-weight: bold;
}
.text-bold i {
font-weight: normal;
}
<div className="text-bold">
<ul>
<li dangerouslySetInnerHTML={{__html: makeBold(item, 'blue')}} />
</ul>
</div>
Make part of a string value for React Element bold
You can achive what you are trying to accomplish using the dangerouslySetInnerHTML
props.
Look at the code below:
function App(props) { const text = { __html: `The start of string <b>${ props.isTrue ? "Bolded" : "Also Bolded" } </b> the end of string.` };
return <span dangerouslySetInnerHTML={text} />;}
const rootElement = document.getElementById("root");ReactDOM.render(<App isTrue={true} />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>
Adding some bold text inside a text string passed as a prop to a component
you should pass jsx to props so that you can use your own class or markup.
<Section1
section1Title={<React.Fragment>Example <span className="bold">title</span></React.Fragment>}
section1Blockquote="Example blockquote"
section1Text="Example text"
/>
in your css file.
.bold {
font-weight: bold;
}
or you can use strong tag directly.
<Section1
section1Title={<>Example <strong>title</strong></>}
section1Blockquote="Example blockquote"
section1Text="Example text"
/>
update: instead of wrapping inside any html tag(span) we can use React.Fragment( shorthand <>) which will not create extra element outside.
How can I bold a part of a text in React.js?
The replace
function is not built for use with JSX, and is converting your virtual DOM nodes to strings.
This overload of string.replace
expects its second argument to be a function returning a string (and if not, it converts it to a string). In this case, you're returning a JSX node from this function, which appears as [object Object]
when it's put through .toString()
- the replace
function then joins the unmatched strings with the outputs from the function, which is the string you show above. This dodgy string is what is output to React, and so that's what it renders.
Instead, you could use repeated calls to string.search
(or at a lower level, regex.match
) to find out the index of each matches (and the matches themselves), and then output an array of the unmatched text and DOM nodes for the matched text.
Such an array might look like:
[
"This text surrounds a ",
<div className="single-result__bold">match</div>,
", but is still in a normal text node"
];
The above array can then be rendered in react/JSX and will appear as you expect.
how can we bold the word before colon like aaaaa bb ccc need to be bold in react js
You can use
var Component = React.createClass({
render: function() {
var text = this.props.text.split(/\s+(?=\w+:)/).map((address, index) =>
<p key={index}>{ address.split(/(?=:)/).map((x,i)=> i===0 ? <b key={i}>{x}</b> : x) } </p> );
return <div className="text">{text}</div>;
}
});
var text = 'aaaaa: lorem ipsum bb: do lor sit amet ccc: no pro movet';
ReactDOM.render(
<Component text={text} />,
document.getElementById('container')
);
p {
margin: 0;
padding: 0;
}
<script src="https://unpkg.com/react@0.14.0/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom@0.14.0/dist/react-dom.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Related Topics
How to Restrict Past Dates in Html5 Input Type Date
The Use of the Triple Exclamation Mark
Javascript - Auto Click on a Button on Page Load
Regex to Find Json Values Without Quotes
How to Display an Iframe on Button Click
Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)
How to Read a Properties File in JavaScript from Project Directory
Checking for Null Is Not Working for Ajax Json Data
Typeerror: Data.Foreach Is Not a Function
Loading Screen Gets Stuck While Processing Http Request
How to Simulate Key Press Events Programmatically
Prevent a White Space in the Beginning of a Input
How to Have Multiple Buttons of Same Id Value and When Click on Any Button the Pop-Up Should Come
How to Change Colour of Text Based on Its Value When a Page Initially Loads
Change Button Color When Click on the Button
Set Values in Input Type Date and Time in JavaScript
How to Split a String With Multiple Separators in JavaScript